我想在URL输入到UITextView的时候调用一个函数。我知道textView.dataDetectorTypes = .link
,但是有没有一个代表或什么东西会被认为是一个链接被触发的时刻?如何在Swift 3中将一个URL输入到UITextView中时调用该函数
我检查了UITextViewDelegate
,但我无法找到任何东西。
我有什么选择?非常感谢帮助。
我想在URL输入到UITextView的时候调用一个函数。我知道textView.dataDetectorTypes = .link
,但是有没有一个代表或什么东西会被认为是一个链接被触发的时刻?如何在Swift 3中将一个URL输入到UITextView中时调用该函数
我检查了UITextViewDelegate
,但我无法找到任何东西。
我有什么选择?非常感谢帮助。
您可以使用UITextViewDelegate
与shouldChangeTextIn
方法,并检查使用NSDataDetector
这里是斯威夫特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
你将需要监听到文本视图的任何更改(通过委托),然后通过NSDataDetector
运行它自己:https://developer.apple.com/reference/foundation/nsdatadetector
完美!那就是我正在寻找的东西。我现在就试试看,一旦完成就会检查答案。非常感谢你 –
这真是太棒了。非常感谢您发布您的解决方案。为我节省了很多时间!并且很棒! –