NSTextField's attributed string is delayed in rendering

爷,独闯天下 提交于 2019-12-07 03:19:35

问题


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?


回答1:


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];



回答2:


As far as I know that's just normal AppKit weirdness.

I've had success using this custom class to render text fields as links, you just add it in interface builder and set its attributed string value like normal:

DSClickableURLTextField

You also have the option of using an NSButton, though that's more of a pain, and you don't get the hand cursor without extra work.



来源:https://stackoverflow.com/questions/8684972/nstextfields-attributed-string-is-delayed-in-rendering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!