我想在将URL输入UITextView时调用函数。我知道textView.dataDetectorTypes = .link
,但是在链接被识别的那一刻会有一个代表或某些内容会被解雇吗?
我已查看UITextViewDelegate
,但我找不到任何内容。
我有什么选择?非常感谢帮助。
答案 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