Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTextField's attributed string is delayed in rendering

I've got an Label (NSTextField) in IB that's bound to a controller. The controller, on awakeFromNIB, sets the attributedStringValue of the label to contain some coloured text and a link or two.

When you see the label it contains the correct string value, but some of the formatting is lost - until you click on the label, and it updates to contain the correct formatting.

I'm using this code to set the value:

[self.testTextField setAllowsEditingTextAttributes:YES];
[self.testTextField setSelectable:YES];
NSMutableAttributedString *linkString = [[NSMutableAttributedString alloc] initWithString:@"hit this "];

[linkString beginEditing];

NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:@"link"];
NSRange range = NSMakeRange(0, [attrString length]);

[attrString addAttribute:NSLinkAttributeName value:[[NSURL URLWithString:@"http://google.com"] absoluteString] range:range];
[attrString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlinePatternDot] range:range];
[attrString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:range];
[linkString appendAttributedString:attrString];

[linkString appendAttributedString:[[NSAttributedString alloc] initWithString:@" to search"]];

[linkString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, [linkString length])];

[linkString endEditing];

[self.testTextField setAttributedStringValue:linkString];

Based on this example, you'll see the string coloured red and in the default Label font. Then when you click on the label the font changes size and face and the link magically renders.

Any ideas on how to get the string to render correctly the first time?

like image 352
d2kagw Avatar asked Dec 30 '11 23:12

d2kagw


1 Answers

I ran into this same problem. The solution I found was to explicitly set the NSFontAttributeName on the attributed string. I created an NSFont object that matched the font I had set in IB for my textfield and set that attribute like so:

NSFont *font = [NSFont fontWithName:@"Lucida Grande" size:(CGFloat)13.0];
[attrString addAttribute:NSFontAttributeName value:font range:range];
like image 193
Mike Knippers Avatar answered Nov 02 '22 19:11

Mike Knippers