如何以编程方式将文本作为NSTextView中的超链接? Swift 4,Xcode 9.4

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何以编程方式将文本作为NSTextView中的超链接? Swift 4,Xcode 9.4相关的知识,希望对你有一定的参考价值。

如何以编程方式将文本作为NSTextView中的超链接?

像这样:

只是click here注册

或者像这样:

只是http://example.com注册

我发现this solution但它只适用于ios,而不适用于macOS

答案

试试这个:

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
]

以上是关于如何以编程方式将文本作为NSTextView中的超链接? Swift 4,Xcode 9.4的主要内容,如果未能解决你的问题,请参考以下文章