【问题标题】:Disable/Enable UIButton inside UITableViewCell called multiple times多次调用 UITableViewCell 内的禁用/启用 UIButton
【发布时间】:2012-11-15 11:07:00
【问题描述】:

这是一个相当简单的情况:

我有自定义的 UITableViewCell 类,它有自己的属性、网点和东西。其中有两个 UIButtons -> LikeDislike。您可以将它们视为喜欢或不喜欢评论按钮。

我已经像这样向它们添加了 IBActions(在 TableViewController 中,而不是 CustomCell 类中):

    - (IBAction)likeComment:(UIButton *)sender {

 CustomTableCell *thisCell = (CustomTableCell *)[[[sender superview] superview] superview]; // to fetch that cell from view
    RSSItem *item = [commentsToDisplay objectAtIndex:indexPath.row];
   //code to set NSUserDefault value for the comment ID, so it can never be voted for again
   [self.tableView reloadData];

}

在 CellForRowAtIndexPath 中,我检查是否选择了当前项目的用户默认设置,如果是,我禁用按钮(您可以喜欢或不喜欢,不能同时禁用,所以所有按钮都需要禁用):

if((/* get NSUserDefault for the ID*/) == YES){
    [cell.likeButton setEnabled:NO];
    [cell.dislikeButton setEnabled:NO];
}

这里,调用了适当的单元格 indexPath,获取的行的项目和项目的 ID 是正确的。

问题是随机按钮(在一些重复使用的单元格中),除了当前选择的一个之外,也被选中(禁用)。如果我尝试通过插座禁用它们,也会发生同样的事情。这当然是不可接受的。我尝试了各种组合,但显然我的想法是错误的。

有什么建议或链接吗?或者如何正确地将这些按钮与动作和位置联系起来。

【问题讨论】:

  • 如果您找到了这个问题的答案,请将其添加为这个问题的答案(并且只是一个答案)。无需编辑您的问题以包含答案。

标签: ios uitableview uibutton


【解决方案1】:

这是解决问题的另一个完美解决方案......

在 tableView 的 CellForRowAtIndexpath 方法中首先为你的按钮设置标签

cell.Yourbutton.tag = [Indexpath row];

// 调用你的 UIButton 事件

[cell.youbutton addTarget:self action:@selector(likeEvent:) forControlEvents:UIControlEventTouchUpInside];

//方法声明

- (void)likeEvent:(UIButton *)sender 
{

UIButton *likeButton =  (UIButton *)sender;

if (likeButton.isSelected) {
    [likeButton  setImage:[UIImage imageNamed:@"like-default.png"] forState:UIControlStateNormal];
}else {
    [likeButton  setImage:[UIImage imageNamed:@"like-active.png"] forState:UIControlStateSelected];
}
[likeButton  setSelected:!likeButton.isSelected];
NSLog(@"like:%d",likeButton.isSelected);

}

【讨论】:

    【解决方案2】:

    我刚刚遇到了同样的问题并找到了一个简单的解决方法。选择的答案不正确。您已经通过使用该 ID 的 NSDefault 来维护表中某个索引的按钮是否需要在其他地方启用或禁用的信息。

    解决这个问题的方法是在

    cellForRowAtIndexPath:
    

    就在你之前

    if((/* get NSUserDefault for the ID*/) == YES){
    [cell.likeButton setEnabled:NO];
    [cell.dislikeButton setEnabled:NO];
    

    }

    始终启用按钮。将此代码放在 else 语句中也可以。

    注意:这可行,但不是最佳解决方案。

    【讨论】:

    • 感谢@Sam 的回答。不久前我已经通过使用标签解决了这个问题。现在已编辑答案。
    【解决方案3】:

    发生这种情况是因为表格单元格被重复使用。查看UITableView 的文档以获取更多信息。要解决此问题,请维护表中某个索引的按钮是否需要在其他位置启用或禁用的信息,然后在 tableView:cellForRowAtIndexPath: 中启用/禁用它们。

    【讨论】:

    • 我知道单元格被重复使用了,这就是这个问题的原因。我不会根据indexPath.row 值禁用按钮,而是将项目的 ID 保存为用户默认值。在tableView:cellForRowAtIndexPath: 中,我首先检查该用户默认值,如果存在该 ID,则禁用按钮。但是,它仍然会禁用多个单元格。
    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多