链接到TextView,可以编辑TextView(Swift 4)

时间:2017-12-10 10:13:24

标签: swift xcode hyperlink uitextview

我有一个TextView。

如何才能使链接工作并且编辑TextView

我怎样才能做到这一点,当我发布一个到TextView的链接时,就可以点击它并重复它(并用不同的颜色突出显示它)。

我尝试在设置中包含Link,但无法编辑TextView。

enter image description here

1 个答案:

答案 0 :(得分:3)

为了能够检测到textView所需的链接,您需要将editable设置为false。您可以做的是在textView中添加手势识别器以检测点击次数,手势识别器将忽略链接上的cliks。以下示例(阅读说明的注释):

class ViewController: UIViewController, UITextViewDelegate {
    // create an outlet for your textView
    @IBOutlet weak var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        textView.delegate = self

        // add a tap gesture to your textView
        let tap = UITapGestureRecognizer(target: self, action: #selector(textViewTapped))
        textView.addGestureRecognizer(tap)

        //add a tap recognizer to stop editing when you tap outside your textView (if you want to)
        let viewTap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
        self.view.addGestureRecognizer(viewTap)
    }

    @objc func viewTapped(_ aRecognizer: UITapGestureRecognizer) {
        self.view.endEditing(true)
    }

    // when you tap on your textView you set the property isEditable to true and you´ll be able to edit the text. If you click on a link you´ll browse to that link instead
    @objc func textViewTapped(_ aRecognizer: UITapGestureRecognizer) {
        textView.dataDetectorTypes = []
        textView.isEditable = true
        textView.becomeFirstResponder()
    }

    // this delegate method restes the isEditable property when your done editing
    func textViewDidEndEditing(_ textView: UITextView) {
        textView.isEditable = false
        textView.dataDetectorTypes = .all
    }
}

textView具有以下属性: enter image description here

here是我创建的示例项目的链接。