I'm using shouldChangeCharactersInRange as a way of using on-the-fly type search.
However I'm having a problem, shouldChangeCharactersInRange gets called before the text field actually updates:
In Objective C, I solved this using using below:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
return YES;
}
However, I've tried writing this in Swift:
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
let txtAfterUpdate:NSString = self.projectSearchTxtFld.text as NSString
txtAfterUpdate.stringByReplacingCharactersInRange(range, withString: string)
self.callMyMethod(txtAfterUpdate)
return true
}
The method still gets called before I get a value?
Swift 3
If you want to pre-process the characters the user typed or pasted, the following solution workes like a charm
Find it here: https://gist.github.com/Blackjacx/2198d86442ec9b9b05c0801f4e392047
Swift 3 & 4
Swift 2.2
Though the
textField.text
property is an optional, it cannot be set to nil. Setting it to nil is changed to empty string withinUITextField
. In the code above, that is whytextFieldText
is set to empty string iftextField.text
is nil (via the nil coalescing operator??
).Implementing
textFieldShouldClear(_:)
handles the case where the text field's clear button is visible and tapped.Swift 4
This method doesn't use
NSString
Note. Be careful when you use a secured text field.
In Swift 3 it would look like this:
stringByReplacingCharactersInRange
return a new string, so how about:To get the exact text in the my UITextField component in Swift 3.0 I used: