ios - iphone UITableViewCell 重复的问题?

查看:124
本文介绍了ios - iphone UITableViewCell 重复的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

因为 cell会复用,所以使用cell的时候会检查一下cell的状态,比如


UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cartCell" forIndexPath:indexPath];

if(cell == nil){
    //do something
    UIImageView *imageView = alloct init
    imageView.tag = tag;
    [cell.contentView addSubview:imageView]
}
else{
    UIImageView *imageView = cell from tag get view
}

但是我的情况是,cell一开始就不为空,于是我这么做:

 if ([cell.contentView subviews].count == 0) {
     // do some thing
 }
 
 

最后我发现,一个table有5个cell全部都在显示区域里面,只有第一个cell是新的,其他都是复用的,这样是不是不对?

讲道理不应该是屏幕内的cell都是独立的,当屏幕外的cell滑动进来才会导致复用么?

解决方案

同意 酷酷的哀殿,补充一下:

- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);

这个方法会默认返回一个非空的cell,如果没有能直接复用的cell,会帮你创建一个cell,所以一般的做法是:

1.创建一个UITableViewCell的子类ACell;

2.ACell重写方法:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // configure cell
    }
}

这个方法在dequeue找不到可复用的cell需要创建新的cell的时候会调用;

3.在tableView中注册这个类(registerNib也可以):

[tableView registerClass:[ACell class] forCellReuseIdentifier:identifier]

4.在cellForRowAtIndexPath的时候直接调用就好:

ACell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
[cell setModel:model];

这篇关于ios - iphone UITableViewCell 重复的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆