重用单元格时需要注意的问题

来源:互联网 发布:上海cda数据分析师培训 编辑:程序博客网 时间:2024/05/21 17:10

1.单元格的内容重叠。解决办法有以下三个:

(1)取消cell的重用机制,通过indexPath来创建cell 将可以解决重复显示问题 不过这样做相对于大数据来说内存就比较吃紧了

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    // 定义唯一标识    static NSString *CellIdentifier = @"Cell";    // 通过indexPath创建cell实例 每一个cell都是单独的    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];    // 判断为空进行初始化  --(当拉动页面显示超过主页面内容的时候就会重用之前的cell,而不会再次初始化)    if (!cell) {        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];    }    // 对cell 进行简单地数据配置    cell.textLabel.text = @"text";    cell.detailTextLabel.text = @"text";    cell.imageView.image = [UIImage imageNamed:@"4.png"];        return cell;}

(2)让每个cell都拥有唯一的标识重用机制是根据相同的标识符来重用cell的,标识符不同的cell不能彼此重用这种方案在上滑时可以重用标识符对应的单元格,但显示内容比较多时内存占用也是比较多的和方案一类似

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    // 定义cell标识  每个cell对应一个自己的标识    NSString *CellIdentifier = [NSString stringWithFormat:@"cell%ld%ld",indexPath.section,indexPath.row];    // 通过不同标识创建cell实例    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    // 判断为空进行初始化  --(当拉动页面显示超过主页面内容的时候就会重用之前的cell,而不会再次初始化)    if (!cell) {        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];    }    // 对cell 进行简单地数据配置    cell.textLabel.text = @"text";    cell.detailTextLabel.text = @"text";    cell.imageView.image = [UIImage imageNamed:@"4.png"];        return cell;}
(3)删除重用的cell的所有子视图,从而得到一个没有特殊格式的cell,供其他cell重用。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    // 定义唯一标识    static NSString *CellIdentifier = @"Cell";    // 通过唯一标识创建cell实例    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    if (!cell) {        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];    }    else    {        while ([cell.contentView.subviews lastObject] != nil) {            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];        }    }    // 对cell 进行简单地数据配置    cell.textLabel.text = @"text";    cell.detailTextLabel.text = @"text";    cell.imageView.image = [UIImage imageNamed:@"4.png"];        return cell;}

2.重用单元格时,一定要注意所有数据是否都已更新(如果不是所有数据都更新,可能出现数组越界问题)



0 0