0

我想让 url 链接在 TextView 中可点击,并让该文本像 iPhone 中的 Notes 应用程序一样可编辑。

这是我尝试的:

    txtVw.dataDetectorTypes = UIDataDetectorTypes.link
    txtVw.isSelectable = true
    txtVw.isEditable = false. // this is set to false to make link text tappable
    txtVw.linkTextAttributes = [.foregroundColor: UIColor.blue, .underlineStyle: NSUnderlineStyle.single.rawValue]
    txtVw.isUserInteractionEnabled = true
    txtVw.delegate = self

    let descTap = UITapGestureRecognizer(target: self, action: #selector(textViewTapped))
    descTap.numberOfTapsRequired = 1
    txtVw.addGestureRecognizer(descTap)

    @objc func textViewTapped(_: UITapGestureRecognizer) {
     txtVw.dataDetectorTypes = []
     txtVw.isEditable = true
     txtVw.becomeFirstResponder()
    }

这里的问题是,如果我将 isEditable 属性设置为 true,则链接未格式化,如果不可编辑,则剩余文本。我想实现与 iPhone 笔记应用程序相同的功能。有没有人遇到过这种情况?任何帮助,将不胜感激。

4

1 回答 1

0

首先你需要有 textView 而不是 Textfield。它们适用于以下编程方式来设置颜色或样式。

 let attributedString = NSMutableAttributedString(string: "I understand and agree to the Terms of Service.", attributes: [
              .font: UIFont.systemFont(ofSize: 12.0, weight: .regular),
              .foregroundColor: UIColor.errorColor,
              .kern: 0.0
            ])
            attributedString.addAttribute(.link, value: "https://policies.google.com/privacy?hl=en-US", range: NSRange(location: 30, length: 17))
            self.termOfServiceTextView.linkTextAttributes = [NSAttributedString.Key.foregroundColor.rawValue: UIColor.errorColor]
            attributedString.addAttribute(.underlineStyle, value: 1, range: NSRange(location: 30, length: 17))
            self.termOfServiceTextView.attributedText = attributedString

现在为了使它可编辑和可点击,需要从情节提要中设置:只需检查EditableSelectable选项。

在此处输入图像描述

于 2021-08-04T07:20:24.503 回答