Предполагая, что вы спрашиваете, как получить событие, когда выбор изменяется в UITextField, вам необходимо добавить наблюдателя в свойство selectedTextRange UITextField
(из протокола UITextInput
).
Вот небольшой пример контроллера представления, который прослушивает такие события для текстового поля:
class MyVC: UIViewController {
var textField: UITextField!
@objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "selectedTextRange" {
if let tf = object as? UITextField {
// This is our event and text field
if let range = tf.selectedTextRange {
print("Updated selection = \(range)")
}
return
}
}
// This isn't the event or the object we care about, pass it on
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
textField = UITextField(frame: CGRect(x: 0, y: 0, width: 300, height: 44))
textField.text = "Hello there. How are you?"
// Options is empty because we don't care about the old range and we can get the new range from the text field
textField.addObserver(self, forKeyPath: "selectedTextRange", options: [], context: nil)
view.addSubview(textField)
}
deinit {
textField.removeObserver(self, forKeyPath: "selectedTextRange")
}
}