最近在好多地方又遇到有人提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;