【问题标题】:Subclassing UITableViewCell correctly?子类化 UITableViewCell 正确吗?
【发布时间】:2010-07-30 04:13:19
【问题描述】:

将 subview 添加到 self 和 or 到 content view 有什么区别?

子视图添加到自己

- (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) {
    UIImage *img = [UIImage imageNamed:@”lol.jpg”]; 
    UIImageView *imgView = [[UIImageView alloc] initWithImage:img]; 
    [self addSubview:imgView];
    [imgView release]; 
    return self;
}

子视图添加到 contentView

- (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) {
    UIImage *img = [UIImage imageNamed:@”lol.jpg”]; 
    UIImageView *imgView = [[UIImageView alloc] initWithImage:img]; 
    [self.contentView addSubview:imgView];
    [imgView release]; 
    return self;
}

【问题讨论】:

    标签: iphone objective-c cocoa-touch uitableview


    【解决方案1】:

    根据Apple docs

    UITableViewCell 对象的内容视图是单元格显示内容的默认超级视图。如果您想通过简单地添加其他视图来自定义单元格,则应将它们添加到内容视图中,以便在单元格进入和退出编辑模式时适当地定位它们。

    通常,当您对由自动调整大小设置处理的内容的大小调整和定位感到满意时,您可以添加到 contentView,并在您需要一些自定义行为等时将 UITableViewCell 子类化。 Apple Table View Programming Guide 中有一个关于customizing UITableViewCells 的精彩部分。

    【讨论】:

      【解决方案2】:

      这是因为当 tableviewcell 进入 editing 模式时,它将向单元格添加 其他控件,例如删除按钮。所以你的内容应该调整大小以便为新控件腾出空间。如果您将子视图直接添加到 tableviewcell 这些编辑控件会遮盖您添加的子视图。进入编辑模式时单元格无法调整其大小(必须保持表格视图的宽度)。但是 contentView 对象可以而且确实可以。这就是为什么您应该将子视图添加到 contentView 对象。

      【讨论】:

        【解决方案3】:

        您应该始终将自定义视图插入单元格contentView。确保你不使用

        cell.textLabel?.text 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-31
          • 2016-04-19
          • 1970-01-01
          相关资源
          最近更新 更多