问题描述
我有一个标签(NSTextField)在IB绑定到控制器。
在awakeFromNIB上,控制器将标签的attributStringValue设置为包含一些彩色文本和一两个链接。
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.
我使用此代码设置值:
[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];
$ b。
然后当你点击标签的字体改变大小和脸和链接神奇地呈现。
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?
推荐答案
我遇到了同样的问题。我发现的解决方案是显式设置NSFontAttributeName上的属性字符串。我创建了一个NSFont对象,它匹配我在IB中为我的文本字段设置的字体,并设置属性如下:
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];
这篇关于NSTextField的属性字符串在呈现方面延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!