swiftmacosnstextview

How to make the text as a hyperlink in NSTextView programmatically? Swift 4, Xcode 9.4


How to make the text as a hyperlink in NSTextView programmatically?

Like this:

Just click here to register

or like this:

Just http://example.com to register

I found this solution but it works only for iOS, not for macOS


Solution

  • Try this:

    let attributedString = NSMutableAttributedString(string: "Just click here to register")
    let range = NSRange(location: 5, length: 10)
    let url = URL(string: "https://www.apple.com")!
    
    attributedString.setAttributes([.link: url], range: range)
    textView.textStorage?.setAttributedString(attributedString)
    
    // Define how links should look like within the text view
    textView.linkTextAttributes = [
        .foregroundColor: NSColor.blue,
        .underlineStyle: NSUnderlineStyle.styleSingle.rawValue
    ]