將動態創建的 UIButton 添加到 NSMutableArray 後,從數組取出修改圖片不生效,原因:_buttons 數組未初始化,addObject: 對 nil 無操作,取出時為 nil。
// viewDidLoad 中
for (int i = 0; i < 3; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[view addSubview:button];
[_buttons addObject:button]; // ❌ _buttons 為 nil,調用被忽略
}
// 後續修改
UIButton *button = [_buttons objectAtIndex:0]; // 返回 nil
[button setImage:thumb forState:UIControlStateNormal]; // 無效果
- (void)viewDidLoad {
[super viewDidLoad];
_buttons = [NSMutableArray array]; // ✅ 必須初始化
// 或 @property 宣告時初始化:@property (nonatomic, strong) NSMutableArray *buttons = [NSMutableArray array];
for (int i = 0; i < 3; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[view addSubview:button];
[_buttons addObject:button];
}
}
// 創建時設置 tag
button.tag = 100 + i;
// 修改時直接從視圖層級查找
UIButton *button = (UIButton *)[self.view viewWithTag:100];
[button setImage:thumb forState:UIControlStateNormal];
viewDidLoad 統一初始化。初始化數組,程序化控件管理才可靠。