UITableViewCell detailTextLabel disappears on scroll

I am using an array of strings that I am setting from detailTextLabel

. Initially all subtitles are set correctly, but if I scroll detailTextLabel

it 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 am using iPhone 6 and iOS 8. I also use storyboard and set style UITableViewCell

to Subtitle

.

+3


source to share


3 answers


OK, now that we have found the problem (with nil text on the face), there are several ways you can fix it.

You don't seem to want the text to be empty. I guess this is because it spells out the cell in a weird way when the title is pushed up but nothing below it. Understandable.

So, you can create a custom subclass UITableViewCell

. In it, you can manage the layout yourself, and if the number is zero, lay it out to one side, and if it has a phone number, indicate it in a different way.

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

In the storyboard, create two prototype cells.



One with type Basic

and give it a reuseIdentifier noPhoneNumberCell

. Another with a type Subtitle

and reuse identifier phoneNumberCell

.

Then in 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;
}

      

Two queues of cells will now be created. One for people with phone numbers and one for people without.

This way you don't confuse the two and avoid the problems you run into.

+4


source


[cell.detailTextLabel sizeToFit];

      



+2


source


UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];



}

      

-2


source







All Articles