如何解决如何检测 URL 是否已粘贴/键入到 UITextView 中?迅捷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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。