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?
If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).
textField(_:shouldChangeCharactersIn:replacementString:)Asks the delegate whether to change the specified text.
A set of optional methods to manage the editing and validation of text in a text field object.
Swift 4, Swift 5
This method doesn't use NSString
// MARK: - UITextFieldDelegate extension MyViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text, let textRange = Range(range, in: text) { let updatedText = text.replacingCharacters(in: textRange, with: string) myvalidator(text: updatedText) } return true } }
Note. Be careful when you use a secured text field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With