Reputation: 13943
How do I trigger the events manually given the UITextField object?
textFieldShouldBeginEditing(_:)
textFieldDidBeginEditing(_:)
textFieldShouldEndEditing(_:)
textFieldDidEndEditing(_:)
In the current scenario. There is some logic which goes into the above callbacks. And there are times when I manually update a textfield
textfield.text = <new text>
And I would like the
textFieldDidBeginEditing
to be trigger, like (hopefully)
textfield.trigger("textFieldDidBeginEditing")
While my approach might not be entirely the right way, the above solution is what would most likely works for me. Although, If I can word my question differently, it would be:
textfield.text = <new value>
Upvotes: 1
Views: 3966
Reputation: 616
Brushing aside the situation you're trying to solve; regardless of wether this is the right approach; you can trigger UITextField events like this:
textField.sendActions(for: UIControl.Event.editingChanged)
Upvotes: 2
Reputation: 57184
To elaborate on my answer and my reasoning:
I don't think it is possible to trigger those kind of events "by hand" - neither should you be able to. It would just cause possibly more problems than it solves. E.g. what should happen with the caret for example, should it be displayed in the textfield?
Therefore I suggest you extract the logic into a second method and call that method from your current code and from the handler
Instead of
func textFieldDidEndEditing(textField: UITextField) {
// your logic is here
let k = 1 + 2
}
func yourCurrentCode() {
// somehow trigger the event "textFieldDidEndEditing"
}
do something like
func textFieldDidEndEditing() {
myLogic()
}
func yourCurrentCode() {
myLogic()
}
func myLogic() {
// your logic should be here
let k = 1 + 2
}
If you would like to be notified every time the value of the UITextField changes you should use the notification
UITextFieldTextDidChangeNotification
Upvotes: 1