gpichler
gpichler

Reputation: 2381

UITableViewCell detailTextLabel disappears when scrolling

I'm using an array of strings where I set the detailTextLabel from. Initially all subtitles are set correctly but if I scroll the detailTextLabel disappears.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"personCell"  forIndexPath:indexPath];

    Person *person = [_persons objectAtIndex:indexPath.row];
    cell.textLabel.text = person.name;
    cell.detailTextLabel.text = person.phone;

    // also tried setNeedsLayout but does not help
    [cell setNeedsLayout];

    return cell;
}

I'm using an iPhone 6 and iOS 8. I'm also using storyboard and set the UITableViewCell style to Subtitle.

Upvotes: 3

Views: 1400

Answers (2)

user1859283
user1859283

Reputation: 11

[cell.detailTextLabel sizeToFit];

Upvotes: 1

Fogmeister
Fogmeister

Reputation: 77651

OK, now that we've found the problem (with the nil phone number text on the person) you could solve it a couple of ways.

It seems that you don't want to set the text to blank. I imagine this is due to the fact that it lays out the cell in an odd way with the title pushed up to the top but nothing underneath it. Understandable.

So, you could create a custom UITableViewCell subclass. In it you can manage the layout yourself and if the number is nil lay it out one way and if it has a phone number lay it out a different way.

An easier way would be to use two different prototype cells instead.

In the storyboard create two prototype cells.

One with type Basic and give it a reuseIdentifier noPhoneNumberCell. The other with type Subtitle and a reuse identifier phoneNumberCell.

Then in the code you can do something like this...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   *)indexPath
{
    Person *person = [_persons objectAtIndex:indexPath.row];
    UITableViewCell *cell;

    if (person.phone) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"phoneNumberCell" forIndexPath:indexPath];

        cell.detailTextLabel.text = person.phone;
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"noPhoneNumberCell" forIndexPath:indexPath];
    }

    cell.textLabel.text = person.name;

    return cell;
}

This will now create two queues of cells. One for people with phone numbers and one for people without.

This way you don't mix the two and so avoid the problem you are facing.

Upvotes: 4

Related Questions