The assigned NSTextField string is delayed while rendering

I have a Label (NSTextField) in IB that is connected to a controller. The controller, on awakeFromNIB, sets the attribatedStringValue attribute of the label to contain colored text and a link or two.

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

I use 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 will see that the string is colored red and the default font is Label. Then, when you click on the label, the font changes size and face, and the link magically displays.

Any ideas on how to wrap a line for the first time?

+6
source share
2 answers

I ran into this problem. The solution I found is to explicitly set NSFontAttributeName in the attribute string. I created an NSFont object that matched the font that I set to IB for my text box, and set this attribute as follows:

 NSFont *font = [NSFont fontWithName:@"Lucida Grande" size:(CGFloat)13.0]; [attrString addAttribute:NSFontAttributeName value:font range:range]; 
+4
source

As far as I know, this is just the usual AppKit weirdness.

I have had success using this custom class to render text fields as links, you just add it to the interface constructor and set its attribute string value, as usual:

DSClickableURLTextField

You also have the option to use NSButton , although this is a pain, and you do not get a hand cursor without extra work.

0
source

Source: https://habr.com/ru/post/904777/


All Articles