Pham Hoan
Pham Hoan

Reputation: 2127

UITableViewCell detailTextLabel doesn't show up even with different cell styles

Here's my code:

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

The problem is when I registerClass for my table, it assumes that my cell style is UITableViewCellStyleDefault. So that's why detailTextLabel doesn't show up. I tested it.

Comment out the registerClass line doesn't work because I don't have any CellIdentifier for dequeueReusableCell. So it will throw some exceptions.

If I'm not using dequeue, it works, but it not the best practice.

AFAIK, table cell couldn't change its style after init. So how can I make the detailTextLabel show up ?

Upvotes: 1

Views: 1554

Answers (1)

matt
matt

Reputation: 534925

The problem is when I registerClass for my table, it assumes that my cell style is UITableViewCellStyleDefault. So that's why detailTextLabel doesn't show up

That is correct. The solution is: do not register UITableViewCell as your class. Register a custom UITableViewCell subclass whose sole purpose in life is that it initializes itself to a different style.

For example, register the MyCell class, which you have defined like this:

@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

Upvotes: 7

Related Questions