iOS开发的正确姿势

【iOS开发】tableView中Button复用解决方案

2016-03-22  本文已影响25239人  纪宝宝

Cell上Button的复用问题


在tableView中,我们常常会有这样的需求,点赞、单选、多选等,

比如我在项目中,遇到的单选,如下:

Snip20160322_22.png
不墨迹了,说说问题

因为复用的问题,我们选中上述图片,当数量很多的时候,你滑动加载出新的,他并不是新建的cell,而是从复用池中取的,所以,就会出现新出来的上面的button,带有之前的状态。

</br>

解决方案:


button的状态存到数组里,每次从数组里读取button的状态。

1.初始化一个存状态的数组

//状态数组
@property (nonatomic, strong) NSMutableArray *btnStatusArr;
//数据源
_dataSource = [NSMutableArray array];

2.初始化状态数组的值,用于等下设置cell上button的状态

for (int i=0; i<_dataSource.count; i++) {
    [self.btnStatusArr addObject:[NSString stringWithFormat:@"%@",i==0?@"1":@"0"]];
}

3.设置cell上button的状态,每次都是从状态数组中取状态

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 [cell.sellButton setTag:1000 + indexPath.row];
 [cell.sellButton addTarget:self action:@selector(chooseSellBankAction:)  forControlEvents:UIControlEventTouchUpInside];
   if ([_btnStatusArr[indexPath.row] isEqualToString:@"1"]) {
      cell.sellButton.selected=YES;
  }else{
      cell.sellButton.selected=NO;
  }
}

4.点击cell上button,更改状态数组中的状态值
- (void)chooseSellBankAction:(UIButton *)button {
for (int i=0; i<_btnStatusArr.count; i++) {
UIButton *btn=[self.view viewWithTag:i+1000];
btn.selected=NO;
_btnStatusArr[btn.tag-1000]=[NSString stringWithFormat:@"%d",btn.selected];
}
button.selected = !button.selected;
_btnStatusArr[button.tag-1000]=[NSString stringWithFormat:@"%d",button.selected];
}

这样就可以了,我做的是单选,多选、点赞的思路也是一样的。

</br>
——————————— 【 MadeBy 纪宝宝 】 ———————————

上一篇 下一篇

猜你喜欢

热点阅读