UITextField How to check if the delete key is pressed

I am implementing a search bar from my local database, which searches with db when the user enters information. The problem is that I concatenated the recent character and the previous ones, and then send it to search. How can I DELETE a character (last) when the back key is pressed. I use

  - (BOOL) textField: (UITextField *) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString *) string

thanks for answers

+6
ios iphone uitextfield
source share
4 answers

You can get the string that should be in the text box after this method:

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 

And that you can probably use neString "as is" to search the database.

If you just want to receive an event when the user deletes some characters in textField, you can check it as follows:

 if ([string length] == 0 && range.length > 0) //Some characters deleted 
+17
source share

for fast users:

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if string.characters.count == 0 && range.length > 0 { // Back pressed return false } return true } 
+3
source share

A better idea is in textField: shouldChangeCharactersInRange: replacementString: set a condition to return NO when there are more characters ...

 if ((range.location == 0) && (string.length == 0)) { NSLog(@"is cleared!"); return NO; } return YES; 
+2
source share
 if (self.textView.text.length > 0) { [self.textView deleteBackward]; } 
0
source share

All Articles