【问题标题】:How to make the text as a hyperlink in NSTextView programmatically? Swift 4, Xcode 9.4如何以编程方式将文本作为 NSTextView 中的超链接?斯威夫特 4,Xcode 9.4
【发布时间】:2019-02-19 23:12:51
【问题描述】:

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

像这样:

只需click here 注册

或者像这样:

只需http://example.com 注册

我找到了this solution,但它仅适用于 iOS,不适用于 macOS

【问题讨论】:

标签: swift macos nstextview


【解决方案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
]

【讨论】:

  • 它有效,谢谢!难道你不知道当我悬停链接时如何将光标更改为指针吗? :)
  • 问题是针对 MacOS 而不是针对 iOS
  • 嗨,在开发 macOS 应用程序的 Swift 5 上,这不会产生可点击的链接。我缺少什么让它工作吗?文本是蓝色的,下划线正确,但由于某种原因无法点击。
【解决方案2】:

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

    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)

【讨论】:

    猜你喜欢
    • 2019-02-21
    • 2017-06-25
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    相关资源
    最近更新 更多