首页 > 自定义tableViewCell按钮状态改变的问题

自定义tableViewCell按钮状态改变的问题

RT,自定义了一个tabelViewCell,里面放了个button,设置了按钮选中和未选中状态的背景图片,然后想要实现点击这个cell的时候就改变按钮的点击状态,

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  //获得点击的cell
  MyCarCell *cell = (MyCarCell *)[self.tableView
      cellForRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row
                                               inSection:indexPath.section]];
  //这里设置按钮的选中状态
  cell.isSeletc = !cell.isSeletc;
  //刷新cell
  [self.tableView reloadRowsAtIndexPaths:@[
    [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]
  ] withRowAnimation:UITableViewRowAnimationNone];
}

点击的时候按钮只是改变了一下状态然后马上恢复原状了,求解


问题分析

cell.isSeletc = !cell.isSeletc;应该设置了按钮的状态更新了UI吧?
紧接着你调用了

  [self.tableView reloadRowsAtIndexPaths:@[
    [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]
  ] withRowAnimation:UITableViewRowAnimationNone];

这样UITableView会回调tableView:cellForRowAtIndexPath:方法去更新cell。如果在这个方法中,你没有设置cell.isSeletc,或者把cell.isSeletc设置为默认值,就会看到你现在看到的效果,闪一下就恢复回去了。

解决

有一个减少大部分这种错误的编程思路,将所有会改变cell的UI变化的设置都放在tableView:cellForRowAtIndexPath:中。其它触发的地方只设置UI变化的状态,不去更新UI。设置好状态以后,使用reloadRowsAtIndexPaths:withRowAnimation:刷新对应的cell。这样既可以解决你现在的问题,也可以很容易的避免cell重用时,经常会碰到的显示错误的BUG。
像本题的例子,[cell setIsSeletc:]中,不要去刷新UI,保存只这个BOOL值,而UI的更新放在tableView:cellForRowAtIndexPath:中完成。

【热门文章】
【热门文章】