如何以编程方式使文本成为NSTextView中的超链接?雨燕4,Xcode 9.4

时间:2018-09-15 10:28:08

标签: swift macos nstextview

如何通过编程使文本成为NSTextView中的超链接?

赞:

  

只需click here即可注册

或类似这样:

  

只需http://example.com即可注册

我发现了this solution,但它仅适用于iOS,不适用于macOS

2 个答案:

答案 0 :(得分: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
]

答案 1 :(得分:0)

如果您需要为链接设置字体大小,请使用此 ->

    let input = "Your string with urls"
      
      let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
      let matches = detector.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
      
      let attributes = [NSAttributedString.Key.font: NSFont.systemFont(ofSize: 15)]
      let attributedString = NSMutableAttributedString(string: input, attributes: attributes)
      if matches.count > 0{
           for match in matches {
                guard let range = Range(match.range, in: input) else { continue }
                let url = input[range]
                
                attributedString.setAttributes([.link: url, .font: NSFont.systemFont(ofSize: 15)], range: match.range)
           
           
           }
      }
      
      youTextView.textStorage?.setAttributedString(attributedString)
相关问题