正确地对UITableViewCell进行子类化?

She*_*lam 9 iphone cocoa-touch objective-c uitableview

将子视图添加到自身和/或内容视图之间有什么区别?

子视图添加到自我

- (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;
}
Run Code Online (Sandbox Code Playgroud)

子视图已添加到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;
}
Run Code Online (Sandbox Code Playgroud)

jer*_*son 25

根据Apple文档:

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

通常,当您对通过自动调整大小设置处理的内容的大小调整和定位感到满意时,可以添加到contentView,并在需要某些自定义行为等时使用UITableViewCell子类.Apple Table View编程指南有一个关于自定义UITableViewCells的很棒的部分.