如何在Swift 3中将URL输入到UITextView中时调用函数

时间:2016-11-30 01:18:29

标签: ios swift

我想在将URL输入UITextView时调用函数。我知道textView.dataDetectorTypes = .link,但是在链接被识别的那一刻会有一个代表或某些内容会被解雇吗?

我已查看UITextViewDelegate,但我找不到任何内容。

我有什么选择?非常感谢帮助。

2 个答案:

答案 0 :(得分:4)

您可以UITextViewDelegate使用shouldChangeTextIn方法并使用NSDataDetector

进行检查

这是我在Swift 3中的工作解决方案

extension ViewController: UITextViewDelegate {

    func checkURL(inputString: String) {
        let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
        let matches = detector.matches(in: inputString, options: [], range: NSRange(location: 0, length: inputString.utf16.count))

        for match in matches {
            let url = (inputString as NSString).substring(with: match.range)
            print(url)
        }
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        checkURL(inputString: textView.text)
        return true
    }
}

NSDataDetector https://www.hackingwithswift.com/example-code/strings/how-to-detect-a-url-in-a-string-using-nsdatadetector

的参考

答案 1 :(得分:1)

您需要收听文本视图的任何更改(通过委托),然后自己通过NSDataDetector运行它:https://developer.apple.com/reference/foundation/nsdatadetector