Reputation: 6384
How can I detect when a UITextField has text pasted into it? I have two textfields that are for a starting and ending address. Once I detect a change in them I ask the user if they want to change their map route/data based on that change. Obviously with the delegate I can get when they type into the field but I am not able to figure out when they paste into it (say they want start and end destination to be the same and they copy from one to the other).
Any help would be appreciated.
Upvotes: 1
Views: 2762
Reputation: 1360
In case anyone (like me) wants a Swift version current as of 02/22:
textField.addTarget(self, action: #selector(textFieldChanged(sender:)), for: UIControl.Event.editingChanged)
@objc func textFieldChanged(sender: UITextField) {
if let textFieldText = sender.text {
// textFieldText contains the changed value
}
}
Works for user typing in the field as well as pasting.
Upvotes: 1
Reputation: 6384
I figured it out. It was actually pretty simple. Just add a change event target onto your textfield:
[textfield addTarget:(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
- (void) textFieldDidChange : (UITextField*) textField {
//something spectacular happens here...
}
This is so simple why wouldn't Apple just make it part of the protocol methods?
Upvotes: 3