2010-07-30 95 views
9

将子视图添加到自我和/或添加到内容视图之间有什么区别?正确地继承UITableViewCell?

子视图添加到自

- (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; 
} 

子视图添加到内容查看

- (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; 
} 

回答

25

按照Apple docs

一个UITableViewCell对象的内容视图是用于内容的默认上海华由单元显示。如果您想通过简单地添加附加视图来自定义单元格,则应该将它们添加到内容视图中,以便在单元格进入和退出编辑模式时适当定位它们。

通常你添加到内容查看时,你是舒服的调整大小和内容的定位由自动调整大小设置被处理,而当你需要一些自定义的行为,这样子类的UITableViewCell。 Apple桌面视图编程指南在customizing UITableViewCells上有很大的章节。

0

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

cell.textLabel?.text 
0

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