問題代碼
[btn2 setImage:[UIImage imageNamed:btn1.currentBackgroundImage] forState:UIControlStateNormal];
// 錯誤:currentBackgroundImage 是 UIImage,非 NSString
修正
[btn2 setImage:btn1.currentImage forState:UIControlStateNormal];
// 直接賦值 UIImage 對象
屬性區別
currentImage:當前顯示的圖片(imageView.image)。
currentBackgroundImage:當前背景圖片(backgroundImageView.image)。
imageForState: / backgroundImageForState::獲取指定狀態下的圖片。
完整示例
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn1 setImage:[UIImage imageNamed:@"icon1.png"] forState:UIControlStateNormal];
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn2 setImage:[UIImage imageNamed:@"icon2.png"] forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(copyImage:) forControlEvents:UIControlEventTouchUpInside];
- (void)copyImage:(UIButton *)sender {
[sender setImage:btn1.currentImage forState:UIControlStateNormal];
}