With Swift, how can I detect a user typing/pasting a URL into a UITextView?
Asked
Active
Viewed 495 times
-1
-
Does this answer your question? [how to know when text is pasted into UITextView](https://stackoverflow.com/questions/12454857/how-to-know-when-text-is-pasted-into-uitextview) – Scott Apr 15 '21 at 22:36
-
@Scott, partly answers the question but only if someone was to paste a url. What if someone typed a url, how can we detect this? – Jabi Apr 16 '21 at 00:01
1 Answers
2
If you don't care if text is pasted or typed you can use this solution:
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
}
If you need to know that it pasted then use this. If someone pastes it would be more than one character. We should avoid to use UIPasteboard because it could freeze in this scenarios and also show uneccesary messages to user.
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
}

omanosoft
- 4,239
- 1
- 9
- 16