ios - 即使使用不同的单元格样式,UITableViewCell detailTextLabel也不会显示

标签 ios objective-c uitableview

这是我的代码:

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

问题是当我为表registerClass时,它假定我的单元格样式为UITableViewCellStyleDefault。这就是为什么detailTextLabel不显示的原因。我测试了

注释掉registerClass行不起作用,因为我没有CellIdentifier的任何dequeueReusableCell。因此它将引发一些异常。

如果我不使用dequeue,它可以工作,但不是最佳实践。

AFAIK,表格单元格在初始化后无法更改其样式。那么,如何显示detailTextLabel呢?

最佳答案

问题是当我为表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

关于ios - 即使使用不同的单元格样式,UITableViewCell detailTextLabel也不会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23986657/

相关文章:

iphone - 新 View Controller 中未调用按钮操作

ios - Skobbler SKMapView 和 UIPanGestureRecognizer

ios - 自动布局。使用动态高度垂直设置两个 View

ios - cordova run ios 已停止工作

ios - 为什么 View Controller 的 header 中没有协议(protocol)声明?

ios - 当点击 UITableView 单元格时,我将如何显示 UIDatePicker?

iphone - 在 IOS 中捕获 Facebook 好友电子邮件 ID

ios - UIPickerView 为空,数据源为 JSON 数组

ios - 表格 View 单元格上的步进器(快速)

objective-c - 获取包含当前行的节号