I need to dynamically set the text and value for a clickable URL in my view.
I’ve got it working using an NSTextView, but it seems ridiculously complicated to set the font and I can’t figure out how to center the text:
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:@"Click me"
attributes:[[NSDictionary alloc] initWithObjectsAndKeys:[NSFont fontWithName:@"Lucida Grande" size:14], NSFontAttributeName, nil]];
[attrString beginEditing];
[attrString addAttribute:NSLinkAttributeName value:@"http://example.com" range:NSMakeRange(0, [attrString length])];
[attrString endEditing];
[[self.downloadLinkTextField textStorage] setAttributedString:attrString];
- Am I doing it wrong? I can’t find anything in the Object Library for URLs.
- Is it possible to center align the link?
You’ve done it correctly. Apple has a handy writeup about this which provides a
Hyperlinkcategory onNSAttributedStringthat you can use if you’re so inclined. Their category also underlines and colorizes the link text.As for centering, that’s a function of the view, and not the text itself. You can use
-[NSText alignCenter:](NSTextis the superclass ofNSTextView), after you have selected your string usingsetSelectedRange:, or if you want all the text in the view to be centered, just use: