Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How shouldChangeCharactersInRange works in Swift?

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?

like image 321
Ryan Avatar asked Sep 02 '14 10:09

Ryan


People also ask

How to limit the number of characters in a UITextField or UITextView?

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).

What is shouldChangeCharactersIn?

textField(_:shouldChangeCharactersIn:replacementString:)Asks the delegate whether to change the specified text.

What is textField delegate in Swift?

A set of optional methods to manage the editing and validation of text in a text field object.


1 Answers

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.

like image 194
Vyacheslav Avatar answered Sep 28 '22 23:09

Vyacheslav