Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField How to check if a delete key is pressed

I am implementing a search bar from my local database that searches from db as user enters info.The issue is that i concat recent character and the previous ones and then send it for search.How can I REMOVE the character (last one) when back key is pressed.I am using

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

Thanks for the replies

like image 640
Qamar Suleiman Avatar asked Apr 01 '11 15:04

Qamar Suleiman


3 Answers

You can get the string that is supposed to be in text field after this method:

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

And that newString you probably can use 'as is' for searching the database.

If you just want to get the event when user deletes some characters in textField - then you can check it the following way:

if ([string length] == 0 && range.length > 0)
  //Some characters deleted
like image 117
Vladimir Avatar answered Nov 14 '22 17:11

Vladimir


for swift 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
}
like image 41
ayalcinkaya Avatar answered Nov 14 '22 16:11

ayalcinkaya


Better idea - in textField:shouldChangeCharactersInRange:replacementString: set up a conditional to return NO when there are no more characters...

if ((range.location == 0) && (string.length == 0))
{        
    NSLog(@"is cleared!");
    return NO;
}

return YES;
like image 2
PostCodeism Avatar answered Nov 14 '22 16:11

PostCodeism