UITableViewCell - 设置单元格的最佳位置

Chr*_*eld 6 uitableview ios

我一直在玩弄定制单元在一个UITableViewController由具有基本单元(BaseCell - 的UITableViewCell的子类),然后BaseCell的子类(Sub1Cell,Sub2Cell,BaseCell的两个子类).

因为子类共享一些相同的功能,如果我完全设置它们

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Run Code Online (Sandbox Code Playgroud)

我开始为每种细胞类型重复代码.将通用设置代码放在实际的自定义UITableViewCell类中是否有一个好地方并且是一种好的做法?目前我写了一个简单的设置方法:

- (void)setupCell
{
    self.picture.layer.cornerRadius = 5.0f;
    self.picture.layer.masksToBounds = YES;
    self.picture.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.picture.layer.borderWidth = 1.0f;
}
Run Code Online (Sandbox Code Playgroud)

一旦我创建了我的单元格,我就一直在调用它:

Sub1Cell *cell = [tableView dequeueReusableCellWithIdentifier:statusCellIdentifier];
[cell setupCell];
Run Code Online (Sandbox Code Playgroud)

有没有可以自动调用的方法?我试过 - (void)prepareForReuse但显然,它并不是每次调用,只有在重用单元格时才会调用它.

有关最佳方法的任何建议吗?

编辑:

似乎每次打电话时都会被调用tableView:cellForRowAtIndexPath.我对创建自定义单元格的正确方法感到困惑.我应该做的事情是:

Sub1Cell *cell = [tableview dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
    cell = [[Sub1Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    [cell setupCell];
}
Run Code Online (Sandbox Code Playgroud)

如果我没有对传递的样式做任何事情,它会影响我的自定义单元格吗?

jrt*_*ton 15

您可以awakeFromNib在您的单元格子类中使用.当从故事板中的原型创建新单元格时,将调用此方法,但在重新使用单元格时则不会.

如果你正在使用原型,那么整个if(cell == nil)就会消失,UITableView会在dequeue方法中为你处理所有这些.