如何检测URL是否已粘贴/键入UITextView?Swift iOS



使用Swift,如何检测用户在UITextView中键入/粘贴URL?

如果你不在乎文本是粘贴还是键入,你可以使用这个解决方案:

func textViewDidChange(textView: UITextView) {
if (urlExists(textView.text))
{
// URL exists...
}
}
func urlExists(_ input: String) -> Bool {
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
for match in matches {
guard let range = Range(match.range, in: input) else { continue }
let url = input[range]
print(url)
return true
}
return false
}

如果你需要知道它是粘贴的,那么就用这个。如果有人粘贴,它将是多个字符。我们应该避免使用UIPasteboard,因为它在这种情况下可能会冻结,还会向用户显示不接受的消息。

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text.count > 1 {
// paste scenario
if (urlExists(text.text))
{
// URL exists...
}
} else {
//normal typing
}
return true
}

最新更新