kender
kender

Reputation: 87151

NSAttributedString in a TableView cell - sometimes displayed as plain text

I have a UITextView in my tableview cell. This is how I assign my NSAttributedString to its content:

- (void)setAttributedMessage:(NSAttributedString *)msg
{
    self.bubbleView.textView.text = nil;
    self.bubbleView.textView.font = nil;
    self.bubbleView.textView.textColor = nil;
    self.bubbleView.textView.textAlignment = NSTextAlignmentLeft;
    self.bubbleView.textView.attributedText = msg;
    self.bubbleView.textView.userInteractionEnabled = NO;
}

And my attributed string contains a message text and a date in smaller font by it, so it's how I create it:

- (NSAttributedString *) attributedTextForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *txt = @"Some text";
    NSMutableAttributedString *a = [[NSMutableAttributedString alloc] initWithString:txt attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16]}];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.timeStyle = NSDateFormatterShortStyle;
    df.dateStyle = NSDateFormatterNoStyle;
    NSString *timestamp = [df stringFromDate:[NSDate date]];
    [a appendAttributedString:[[NSAttributedString alloc] 
           initWithString:[NSString stringWithFormat:@"     %@", timestamp]
               attributes:@{NSFontAttributeName: [UIFont italicSystemFontOfSize:10]}]];

    return [[NSAttributedString alloc] initWithAttributedString:a];
}

What I'm getting, when displaying the Table View, is a plain text - no change of font size or no italics with date. When the cell is redisplayed though it gets displayed properly. So When I scroll the cell out of the screen and get it back there, it's OK. I could also reload the table view to force re-displaying, but this solution sounds like a really lame one.

Any idea what's going on there?

Upvotes: 3

Views: 1849

Answers (3)

Sikander
Sikander

Reputation: 483

I fixed it by setting table data in viewDidLoad and then refreshing my table view inside viewDidAppear method.

Upvotes: 0

Halpo
Halpo

Reputation: 3134

Here was my solution: this forces the label to update on the next operation cycle (I imagine it needs to do some sort of setup in the first instance)

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [cell.label setAttributedText:cellString];
}];

Upvotes: 1

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

You may not like it, but the best solution is really the "lame" one:

[yourTableView reloadData];

That way, new views will be generated for all (visible) entries, especially the on-screen ones.

Upvotes: 1

Related Questions