【问题标题】:How to replace word in textView with button UIKit如何用按钮 UIKit 替换 textView 中的单词
【发布时间】:2021-10-12 10:32:50
【问题描述】:

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

【问题讨论】:

  • 您可以使用 UILabel 的属性轻击手势和属性文本而不是文本视图。“但它应该显示另一个 ViewController”你能清除这一点吗?
  • 当我按下“all”这个词时,它应该呈现另一个viewController。我看到了如何使用链接执行此操作,但是当我按下“全部”字时我需要运行我的函数

标签: ios swift uibutton uikit uitextview


【解决方案1】:

我做到了:

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
}

【讨论】:

    猜你喜欢
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 2020-03-01
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多