ios - 更新 TableViewCell 中的 UIButton State 会改变其他行

标签 ios objective-c uitableview uibutton

我的表格 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/

相关文章:

滚动列表时的iOS动画按钮

android - cordova 联系人插件 - 电子邮件为空

swift - 我将如何限制 tableview 中的项目数量并自动加载更多?

ios - 如何在 Swift iOS 中关闭上一个 View Controller 并移至下一个 View Controller

ios - 如何制作这样的动画?

iphone - 如何将 Xcode 4 项目修改为独立于机器的 Visual Studio 或 Eclipse 行为

ios - 发现 UIActivityViewController 支持的所有端点,如微信、KaKao、Line 等?

c++ - Xcode 调试器 : What does the blue italic text mean?

iphone开发: controlling UITableViewCell

ios - 自动布局约束警告 “Will attempt to recover by breaking constraint”