最近在好多地方又遇到有人提tableview的复用问题,觉得还是说下自己的理解,希望能有帮助!
之前就想写自己关于复用的想法,拖了这么久,又有人被困惑,所以就写了。
事实上复用问题的本质是cell上面的控件的内容指针没有重指向、button事件重复添加等!
比如:指针重指向:cell.textLabel.text = model.name;这个就是label上内容的指针重指向,所以只要model有东西,就不会出现问题;
解决方法1:model标记:
(1) 从复用队列取出cell:
InvesmentRedCell *cell = [tableView cellForRowAtIndexPath:indexPath];
(2) 对当前显示的cell做一些处理,比如在点击的时候让其他cell中控件颜色变化等等: for (InvesmentRedCell *tempCell in _tableviewInvestmentRed.visibleCells) { tempCell.imgUse.highlighted = NO; tempCell.lblAmount.textColor = [UIColor colorWithRed:0.53 green:0.53 blue:0.53 alpha:1]; tempCell.lblExpiredDate.textColor = [UIColor colorWithRed:0.53 green:0.53 blue:0.53 alpha:1]; }
(3)遍历数组,把model的选择状态改变 for (MyWelfareModel *tempModel in _arrInvesmentRed) { tempModel.isSelect = NO; }
(4) 正常处理点击后的状态: tempDataModel.isSelect = YES; cell.imgUse.highlighted = YES; cell.lblAmount.textColor = _selectedColor; cell.lblExpiredDate.textColor = _selectedColor; _couponId = tempDataModel.couponid; _selectedModel = tempDataModel; NSInteger amount = [_amountCell.valueTextFied.text integerValue] - _selectedModel.amount.integerValue; if (amount >= 0) { _strInputAmout = [NSString stringWithFormat:@"%ld",(long)amount]; } else { _strInputAmout = @"0"; } 解决办法2:移除点击事件重新添加 (1)取出复用队列中的cell
VideoDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifer forIndexPath:indexPath]; VideoDetailModel *model = self.modelArray[indexPath.row]; cell.model = model;
(2)移除取出cell上的button点击事件 [cell.like removeTarget:self action:@selector(likeButton:) forControlEvents:UIControlEventTouchUpInside];
(3)重新添加事件 [cell.like addTarget:self action:@selector(likeButton:) forControlEvents:UIControlEventTouchUpInside]; cell.like.tag = 2000+indexPath.row; return cell;
解决办法3:使用block解决:
(1)cell中声明一个block属性
@property (nonatomic, copy) void (^moreButtonClickedBlock)(NSIndexPath *indexPath);
(2)cell中添加button事件
_moreButton = [UIButton new]; [_moreButton setTitle:@"显示全部" forState:UIControlStateNormal]; [_moreButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; [_moreButton addTarget:self action:@selector(moreButtonClicked) forControlEvents:UIControlEventTouchUpInside]; _moreButton.titleLabel.font = [UIFont systemFontOfSize:14];
(3)button点击事件
- (void)moreButtonClicked { if (self.moreButtonClickedBlock) { self.moreButtonClickedBlock(self.indexPath); } }
(4)布局cell时
DemoVC9Cell *cell = [tableView dequeueReusableCellWithIdentifier:kDemoVC9CellId];
||记得传入点击位置,在第三步block回传 cell.indexPath = indexPath; __weak typeof(self) weakSelf = self; if (!cell.moreButtonClickedBlock) { [cell setMoreButtonClickedBlock:^(NSIndexPath *indexPath) { Demo9Model *model = weakSelf.modelsArray[indexPath.row]; model.isOpening = !model.isOpening; [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; }]; } cell.model = self.modelsArray[indexPath.row]; return cell;
|