如何用按钮 UIKit 替换 textView 中的单词

How to replace word in textView with button UIKit

我有带有文本的 UITextView:“我接受所有文档”,我需要用蓝色按钮(如链接)替换单词“全部”,但它应该显示另一个 ViewController。我怎样才能做到这一点?顺便说一句,文本是可本地化的 像这样

我这样做了:

private func setupTextView() {
    let attributedString = NSMutableAttributedString(
        string: "I accept all docs.",
        attributes: [
            .font: yourFont,
            .foregroundColor: .black
        ]
    )
    
    attributedString.setSubstringAsLink(substring: "all", linkURL: "dummyURL")
    configureTextView()
    textView.attributedText = attributedString
}

private func configureTextView() {
    let linkAttributes: [NSAttributedString.Key: AnyObject] = [.foregroundColor: .blue]
    
    textView.isScrollEnabled = false
    textView.textContainerInset = UIEdgeInsets(top: 0, left: -5, bottom: 0, right: 0)
    textView.linkTextAttributes = linkAttributes
    
    textView.isSelectable = true
    textView.isEditable = false
    textView.delegate = self
    textView.isUserInteractionEnabled = true
}

private extension NSMutableAttributedString {
    // Set part of string as URL
    func setSubstringAsLink(substring: String, linkURL: String) {
        let range = self.mutableString.range(of: substring)
        if range.location != NSNotFound {
            self.addAttribute(NSAttributedString.Key.link, value: linkURL, range: range)
        }
    }
}

extension ViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        let urlString = URL.absoluteString
    
    if urlString == "dummyURL" {
        do whatever you want
    }

    return false
}