I am trying to create a simple NSTextField
where the entire text content should be a link. The text field is created/positioned in Interface Builder and later propagated with actual data by the view controller. However, the text field does not display my attributed string.
In order to keep things neat and tidy, I subclassed NSTextField
like so:
public class MyLink: NSTextField {
private var linkRange: NSRange?
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
public func setLinkContent(text: String, to url: URL, range: NSRange?) {
allowsEditingTextAttributes = true
isSelectable = true
let attributedLink = NSMutableAttributedString(string: text)
self.linkRange = range ?? NSRange(location: 0, length: text.count)
attributedLink.addAttribute(.link, value: url, range: self.linkRange!)
attributedLink.addAttributes([
.foregroundColor: NSColor.red,
.underlineStyle: NSUnderlineStyle.single,
.cursor: NSCursor.pointingHand,
.font: NSFont.systemFont(ofSize: 16)
], range: self.linkRange!)
self.attributedStringValue = attributedLink
}
}
To put things in perspective, the view controller calls setLinkContent
to propagate the text field data. And after that - nothing (see image). You see that the text field is there because of the blue background color I set, but the actual text is not propagated.
Configuration of the TextField in IB: