Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel Attributed Text rendering incorrectly

I've been setting a UILabel using attributed text to get the font outlining that I want, and I change the UILabel's attributedText property fairly often. It seems that roughly 50% of the time it appears to render the new text OVER the old text without removing the old one. Right now my code looks like this:

// Attributes initialization
self.labelAttributes = [NSMutableDictionary dictionary];
[self.labelAttributes setObject: [UIFont fontWithName:@"Helvetica Neue" size:21] forKey: NSFontAttributeName];
[self.labelAttributes setObject: [UIColor whiteColor] forKey: NSForegroundColorAttributeName];
[self.labelAttributes setObject: [NSNumber numberWithFloat: -3.0] forKey: NSStrokeWidthAttributeName];
[self.labelAttributes setObject: [UIColor blackColor] forKey: NSStrokeColorAttributeName];

// Clear UILabel attributedString
self.userLabel.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:self.labelAttributes];
// Also attempted this with nil;


// Set UILabel to string, where self.userName and self.userAge are just regular strings. 
NSString *labelString = [NSString stringWithFormat:@"%@, %@", self.userName, self.userAge];
self.userLabel.attributedText = [[NSAttributedString alloc] initWithString:labelString attributes:self.labelAttributes];

When it works, it looks like this:

enter image description here

When it doesn't work, it looks like this:

enter image description here

This appears to be the last user's name, plus the current user's name overlayed on top of each other.

I can't figure out a good way to guarantee the label is cleared, and am not sure how to debug it. (I've tried using visual debugging in XCode 6, but it still thinks it's just one label, with the new user's text as the text attribute.)

like image 241
Mic Fok Avatar asked Jun 23 '26 13:06

Mic Fok


1 Answers

It should already be correct by default but you could try it anyway:

self.userLabel.clearsContextBeforeDrawing = YES;
self.userLabel.contentMode = UIViewContentModeRedraw;
like image 87
fluidsonic Avatar answered Jun 25 '26 01:06

fluidsonic