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

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;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容