如何在单击时运行自定义功能的 UITextView 中添加超链接文本

How to add hyperlinked text in UITextView which runs custom function when clicked

如何在 UITextView 中添加超链接文本,以便在单击它时调用我的应用程序中的自定义函数。基本上,我的目的是显示一个小弹出窗口 window,提供有关点击词的更多信息,类似于维基百科的工作方式 –

我在这篇 Hacking With Swift article 中读到您可以在属性文本中“使用自定义 URL 方案,例如 yourapp://”,但我很困惑 yourapp://...链接到您应用程序中的特定功能?我的 URL 是什么?

他们在文章中谈到的代码是:

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet var textView: UITextView!

    override func viewDidLoad() {
        let attributedString = NSMutableAttributedString(string: "Want to learn iOS? You should visit the best source of free iOS tutorials!")
        attributedString.addAttribute(.link, value: "https://www.hackingwithswift.com", range: NSRange(location: 19, length: 55))

        textView.attributedText = attributedString
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL)
        return false
    }
}

你的 URL 可以是任何你想要的,只要你有办法在你的 shouldInteractWith 函数中 parse/compare 它:

例如,您可以做到 myapp://ACTION_NAME

class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet var textView: UITextView!

    override func viewDidLoad() {
        let attributedString = NSMutableAttributedString(string: "Want to learn iOS? You should visit the best source of free iOS tutorials!")
        attributedString.addAttribute(.link, value: "myapp://action1", range: NSRange(location: 19, length: 55))

        textView.attributedText = attributedString
    }

    func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        switch url.absoluteString {
        case "myapp://action1":
           //perform some sort of action here
           break
        case "myapp://action2":
           //perform another sort of action here
           break
        default:
           //if it isn't a link that is recognized by the app, assume it should get opened by the system instead
           UIApplication.shared.open(url, options: [:])
        }
        
        return false
    }
}

以上只是最基本的概念。在实际应用程序中,我可能会做更多的工作来比较 URLs——也许首先查看 url.scheme 以检查它是否等于 myapp 然后拆分动作名称出来。您还可以制作一个 enum 操作类型,使整个事情更加安全。