繁体   English   中英

如何确定dequeueReusableCellWithIdentifier返回的单元格是否在iOS 6中重用?

[英]How do I determine if a cell returned by dequeueReusableCellWithIdentifier is being reused in iOS 6?

我正在向cellForRowIndexPath中的单元格添加项目(例如手势识别器,子视图)。 如果重复使用单元格(大概是),我不想添加这些,所以有没有办法轻松判断单元格是新的还是被重用?

单元原型在故事板中定义。

我没有为单元格使用自定义子类(看起来像是矫枉过正)。 我正在使用单元格标记来识别子视图,因此无法使用它。

我可以使用iOS 6之前的方法,但肯定有更好的方法来做这么简单的事情吗?

我在网上找不到任何东西,所以害怕我可能会对某些东西感到困惑 - 但搜索起来很困难。

解决这个问题的最简单方法是检查是否存在需要添加的内容。

因此,假设您的单元格需要具有标记42的子视图(如果它尚未存在)。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    UIView *subview = [cell viewWithTag:42];
    if (!subview) {
       ... Set up the new cell
    }
    else {
       ... Reuse the cell
    }
    return cell;
}

与使用iOS6之前(没有注册类)的方法相比,它可能有点过分,但如果你真的想坚持下去,你可以使用相关的对象

#import <objc/objc-runtime.h>

static char cellCustomized;

...
-(UITableViewCell *)getCell
{
    UITableViewCell *cell = [tableView dequeueReusableCellForIdentifier:myCell];
    if(!objc_getAssociatedProperty(cell, &cellCustomized)) {
        [self setupCell:cell];
        objc_setAssociatedProperty(cell, &cellCustomized, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return cell;
}

...

(未测试)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM