我的表格 View 在每一行内包含一个 uibutton,根据用户是否已兑换它,我想更改它的图像以及它是禁用还是启用。
当用户购买商品时(比如始终位于第一行的商品 0),我想通知我的应用它应该切换图像并禁用特定行的按钮。我正在使用 NSUserDefaults 来提醒我的 tableView。
换句话说,如果用户点击项目 0,系统会询问他们是要兑换还是取消,如果用户按下兑换,我会执行以下操作:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"itemZeroRedeemed"];
[storeTableView reloadData];
在我的 cellForRowAtIndexPath 中我这样做:
if([[NSUserDefaults standardUserDefaults] boolForKey:@"itemZeroRedeemed"]) {
if(indexPath.row == 0) {
[cell.productInfoButton setBackgroundImage:[UIImage imageNamed:@"itemUnlocked"] forState:UIControlStateNormal];
cell.productInfoButton.enabled = NO;
}
}
它完美地工作,因为它正确地更新了 tableView 和行,尤其是在稍后返回时。我的问题是列表项 5 的下方也正在使用新的按钮状态进行更新。由于我只想更新指定的按钮,我该如何解决这个问题?
最佳答案
问题是由于单元重用机制引起的。对于每个单元格,您应该像这样重置默认状态:
if([[NSUserDefaults standardUserDefaults] boolForKey:@"itemZeroRedeemed"] && indexPath.row == 0) {
[cell.productInfoButton setBackgroundImage:[UIImage imageNamed:@"itemUnlocked"] forState:UIControlStateNormal];
cell.productInfoButton.enabled = NO;
} else {
[cell.productInfoButton setBackgroundImage:[UIImage imageNamed:@"__DEFAULT_IMAGE__"] forState:UIControlStateNormal];
cell.productInfoButton.enabled = YES;
}
关于ios - 更新 TableViewCell 中的 UIButton State 会改变其他行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22892282/