ios - iphone UITableViewCell 重复的问题?
高洛峰
高洛峰 2017-04-18 09:16:22
0
4
411

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
伊谢尔伦

Agree cool Ai Dian, add:

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

This method will return a non-empty cell by default. If there is no cell that can be directly reused, it will help you create a cell, so the general approach is:

1. Create a subclass ACell of UITableViewCell;

2.ACell rewriting method:

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

This method will be called when dequeue cannot find a reusable cell and needs to create a new cell;

3. Register this class in tableView (registerNib can also be used):

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

4. Just call it directly when cellForRowAtIndexPath:

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

It is recommended that you reuse code by inheriting UITableViewCell. And initialize the subview in - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier.

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

  
阿神

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

 // do some thing

}This judgment will never be true, the cell comes with some subviews

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

}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template