suchen

Heim  >  Fragen und Antworten  >  Hauptteil

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滑动进来才会导致复用么?

高洛峰高洛峰2888 Tage vor418

Antworte allen(4)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:18:22

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

    - (__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];

    Antwort
    0
  • 怪我咯

    怪我咯2017-04-18 09:18:22

    建议你通过继承 UITableViewCell 的方式来重用代码。并在- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier中初始化子视图。

    -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
        if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
            self.selectionStyle = UITableViewCellSelectionStyleNone;
    
      

    Antwort
    0
  • 阿神

    阿神2017-04-18 09:18:22

    if ([cell.contentView subviews].count == 0) {

     // do some thing

    }这个判断永远不成立吧,cell自带一些子视图

    Antwort
    0
  • PHP中文网

    PHP中文网2017-04-18 09:18:22

    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cartCell"];
    }
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.tag = tag;
    [cell.contentView addSubview:imageView]

    }

    Antwort
    0
  • StornierenAntwort