user4151918
user4151918

Reputation:

Why does a label's text alignment and color revert to default values after reloadData?

I am using the basic (default) style for my storyboard tableView cell. Within the storyboard, I've set the built-in label's textAlignment to center, and textColor to grey.

The first time the cell is shown, the label's text alignment and color match the storyboard values: Label initially appears with storyboard values

When the tableView data is reloaded (due to a content size change), the text alignment and color may revert to default (left text alignment, black text color) values. Label properties revert to default values after reloadData

Is this an iOS 8 issue? I don't recall needing to set textAlignment or textColor in code with iOS 7. If it matters, the cells are using self-sizing.

- (void)viewDidLoad {
    . . .
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44.0;
}

- (void)contentSizeChanged:(NSNotification *)__unused notification {
    [self.tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"No Results" forIndexPath:indexPath];

    cell.textLabel.text = ([indexPath row] == 2) ? @"No Results" : @"";
    cell.textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];

    // Must set alignment/color, or the properties for a built-in (basic) cell style
    // may revert to default values when the tableView data is reloaded.

    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.textColor = [UIColor colorWithWhite:0.8f alpha:1.0f];

    return cell;
}

Upvotes: 0

Views: 972

Answers (1)

user4151918
user4151918

Reputation:

This apparently is a recurring issue with UILabel.

Formatting properties set in the storyboard are lost when the label's text changes. The workaround is to set the label's textAlignment and textColor in code after setting its text.

This shows up in iOS 7 beta, was fixed, and apparently has resurfaced in iOS 8.

There's an OpenRadar mention of this problem, along with a thread on Apple's Developer Forums. (Developer Program membership required.)

I'll be filing a bug report to track the status of this issue.

Upvotes: 1

Related Questions