Reputation: 2205
How to create an event when UITextfield.selectedTextRange was changed?
I did not found any delegate method for that. Maybe I can create custom observer somehow? I cannot figure out how to do that.
The goal is to trigger some method when selectedTextRange in UITextfield was changed and get a pointer to that UITextfield also to work with target text field inside.
I've tried to override selectedTextRange but it's being triggered in real time many times while dragging cursor. And method triggered is heavy enough to cause UI slow down when triggered 100 times per second.
Upvotes: 2
Views: 1130
Reputation: 2217
For >= iOS 13
You can accomplish this by implementing the textFieldDidChangeSelection:
function with declaring a local variable that will store the most recent selected text range of a TextField. You need to store the last selection so you get notified only by new selection, and not by other changes of the TextField(for example by typing).
class MyViewController: UIViewController {
private var lastSelectedText = ""
// Rest of your MyViewController code
}
extension MyViewController: UITextFieldDelegate {
func textFieldDidChangeSelection(_ textField: UITextField) {
if let textRange = textField.selectedTextRange, let selectedText = textField.text(in: textRange), selectedText != lastSelectedText {
lastSelectedText = selectedText
// Handle change of selectedText or selectedTextRange
}
}
}
For iOS 12 >=
As you mentioned you can override the selectedTextRange
property of the UITextField. I just tested it and it works smooth for every cursor change.
class MyTextField: UITextField {
override var selectedTextRange: UITextRange? {
get {return super.selectedTextRange}
set {
// Handle newValue here
super.selectedTextRange = newValue
}
}
}
Upvotes: 1