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

问题描述 投票:2回答:1

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

像这样:

只是click here注册

或者像这样:

只是http://example.com注册

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

swift macos nstextview
1个回答
1
投票

试试这个:

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
]
© www.soinside.com 2019 - 2024. All rights reserved.