美文网首页iOS开发实录实用轮子专题:临时区
TableViewCell复用出现数据重复加载解决办法

TableViewCell复用出现数据重复加载解决办法

作者: 简简单单写书 | 来源:发表于2017-03-08 18:49 被阅读850次

TableViewCell复用出现数据重复加载解决办法

用tableview的时候特别容易会出现cell的数据重复问题,所以就整理了下解决办法,以后用起来方便,同时也希望对大家有所帮助。

第一种cell的复用写法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

UITableViewCell *cell = [tableView dequeueReusableCellWithReuseIdentifier:kIdentifier forIndexPath:indexPath];

return cell;

}

这种复用写法当出现数据重复的时候可以用下面的解决方法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

UITableViewCell *cell = [tableView dequeueReusableCellWithReuseIdentifier:kIdentifier forIndexPath:indexPath];

for(UIView *view in cell.subviews){

if(view){

[view removeFromSuperview];

}

}

return cell;

}

第二种cell的复用写法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

UITableViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kIdentifier];

if (!cell) {

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

}

return cell;

}

当用这种写法复用cell的时候,出现数据重复,可以用以下方法解决

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

// 定义唯一标识

static NSString *CellIdentifier = @"Cell";

// 通过indexPath创建cell实例 每一个cell都是单独的

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

if (!cell) {

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

}

return cell;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

// 定义cell标识  每个cell对应一个自己的标识

NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",indexPath.section,indexPath.row];

UITableViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier];

if (!cell) {

cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

}

return cell;

}

相关文章

网友评论

    本文标题:TableViewCell复用出现数据重复加载解决办法

    本文链接:https://www.haomeiwen.com/subject/lfutvttx.html