我会避免将你的单元格的布局和构建放入cellForRowAtIndexPath
.
要以编程方式创建自定义单元格,您应该首先创建一个UITableViewCell
子类。
添加到它labels
, imageViews
等等...添加为子视图cell.contentView
.
以编程方式
i.e.
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 21)];
[self.contentView addSubview:_label];
}
return self;
}
如果你想对单元格进行布局,那么在MyCell
你可以做的课...
- (void)layoutSubViews
{
[super layoutSubviews];
// layout stuff relative to the size of the cell.
}
然后在tableViewController
你需要注册细胞类别...
In viewDidLoad
...
[self.tableView registerClass:[MyCell class] forCellReuseIdentifier:@"MyCellIdentifier"];
使用界面生成器
仍然创建自定义子类,但也创建一个同名的 xib 文件。然后,在您的 xib 文件中,您可以连接插座,而不必在单元的 init 中创建它们。 (如果你这样做,那么 init 无论如何都不会被调用)。
您唯一需要的其他更改是viewDidLoad
您需要为单元而不是班级注册笔尖。
像这样...
UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"MyCellIdentifier"];
然后其他一切都一样。
使用细胞
要使用您为其创建子类的单元格...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCellIdentifier"];
[self configureCustomCell:(MyCell*)cell atIndexPath:indexPath];
return cell;
}
- (void)configureCustomCell:(MyCell*)cell atIndexPath:(NSIndexPath *)indexPath
{
// do all you logic of getting any info from arrays etc in here.
cell.label.text = @"Blah".
}
SUMMARY
这样做意味着您的 tableviewcontroller 只对将内容放入单元格感兴趣。如果你把构建细胞的所有逻辑都放在一起,一切都会变得非常混乱。
这也意味着您不必处理大量不同的标签来保存和检索不同的 UI 元素。