即使具有不同的单元格样式,UITableViewCell detailTextLabel也不会显示

Pha*_*oan 1 objective-c uitableview ios

这是我的代码:

- (UITableView *)table {
    if (!_table) {
        _table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [_table setDelegate:self];
        [_table setDataSource:self];
        [_table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    }
    return _table;
}


- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (!cell)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    else

    [self configureCell:cell forRowAtIndexPath:indexPath];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

问题是当我registerClass为我的桌子时,它假定我的细胞样式是UITableViewCellStyleDefault.所以这就是为什么detailTextLabel不出现.我测试了它.

注释掉该registerClass行不起作用,因为我没有任何CellIdentifier用途dequeueReusableCell.所以它会抛出一些例外.

如果我不使用dequeue,它可以工作,但这不是最好的做法.

AFAIK,表格单元格在初始化后无法改变其样式.那我该如何制作detailTextLabel秀呢?

mat*_*att 7

问题是当我registerClass为我的桌子时,它假定我的细胞样式是UITableViewCellStyleDefault.所以这就是为什么detailTextLabel不出现

那是正确的.解决方案是:不要将UITableViewCell注册为您的类.注册一个自定义UITableViewCell子类,其唯一目的是将其自身初始化为不同的样式.

例如,注册您已定义的MyCell类,如下所示:

@interface MyCell:UITableViewCell
@end
@implementation MyCell
-(id)initWithStyle:(UITableViewCellStyle)style
   reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:UITableViewCellStyleValue2 // or whatever style you want
                reuseIdentifier:reuseIdentifier];
    return self;
}
@end
Run Code Online (Sandbox Code Playgroud)

  • 但我的观点是,如果你要注册一个类,那么子类是决定风格的唯一方法.Apple在创建整个"注册类"机制时犯了一个错误.他们应该允许你注册一个类_and_设置一个样式,但他们没有. (2认同)