写这篇文章是因为在项目中遇到了这个问题,,所以拿下来和大家一起分享,平常一直没有因为复用问题而导致数据复用混乱,
先看看效果图:
出现了旧的数据,所以现在这个问题就不能在使用registerNib注册xib方法了,一般复用出现数据混乱可能原因就是cell中包含UITextField和UICollectionView类型的数据时,出现数据混乱的情况比较大,这时候我们就需要做一些特别得操作,
思路:1:每次拿到cell进行判断是否为nil
2:为nil就重新创建
3:不为nil时就删除所有的子视图
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
HistoryModel * model = self.CellModelArr[indexPath.row];
// historyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"historyCell" forIndexPath:indexPath];
historyCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//解决xib复用数据混乱问题
if (nil == cell) {
cell= (historyCell *)[[[NSBundle mainBundle] loadNibNamed:@"historyCell" owner:self options:nil] lastObject];
}else{
//删除cell的所有子视图
while ([cell.contentView.subviews lastObject] != nil)
{
[(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
}
}
// historyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"historyCell"];
// if (cell == nil) {
// cell = [[historyCell alloc] init];
// }
cell.IsBuy.hidden = YES;
cell.hisModel =model;
return cell;
}
最后运行就发现这种解决方法是没毛病