利用tableView重用机制时避免内容重复显示

问题:

tableView是项目中常用的控件,若如下配置,超过页面显示的内容会重复出现:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通过唯一标识创建cell实例
    static NSString *ID = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    // 判断为空进行初始化  --(当拉动页面显示超过主页面内容的时候就会重用之前的cell,而不会再次初始化)
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
    
    return cell;
}

解决:

方法1:取消重用机制,通过indexPath来创建cell

利弊:解决重复显示问题,但如果数据比较多,内存就比较吃紧

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通过唯一标识创建cell实例
    static NSString *ID = @"Cell";
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // 判断为空进行初始化  --(当拉动页面显示超过主页面内容的时候就会重用之前的cell,而不会再次初始化)
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
    
    return cell;
}
方法2:取消重用机制,让每个cell有一个独立的标识符,因为重用机制是根据相同的标识符来重用cell的

利弊:解决重复显示问题,但如果数据比较多,内存同样也会比较吃紧

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通过唯一标识创建cell实例
    NSString *ID = [NSString stringWithFormat:@"CellIdentifier%zd%zd", indexPath.section, indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    // 判断为空进行初始化  --(当拉动页面显示超过主页面内容的时候就会重用之前的cell,而不会再次初始化)
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
    
    return cell;
}
方法3:删除最后一个显示的cell的所有子视图,得到一个没有空的cell,供其他cell重用。

利弊:解决重复显示问题,重用了cell相对内存管理来说是最好的方案

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 通过唯一标识创建cell实例
    static NSString *ID = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    // 判断为空进行初始化  --(当拉动页面显示超过主页面内容的时候就会重用之前的cell,而不会再次初始化)
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }else {
        //当页面拉动的时候 当cell存在并且最后一个存在 把它进行删除
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
    
    return cell;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容