views:

56

answers:

2

Hi, does anyone know how to test when the last character in a UISearchBar is deleted. i.e. you type ...

Gary > return "Gary"
Gar  > return "Gar"
Ga   > return "Ga"
G    > return "G"
     > return ???

.

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self FG_Filter:searchText];
}

I was thinking it would be @"" but I am having trouble getting that to work.

many thanks

Gary

A: 

Put

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range
             replacementText:(NSString *)text

in your delegate and test if

[text length] == 0 && range.location == [searchBar.text length] - 1
mvds
+2  A: 

Actually, it returns nil. (Or at least it did when I wrote my searchBar:textDidChange:.)

But writing code that assumes that is probably foolish. Apple could change it to return @"" next release. Instead, you're better off checking for what you actually care about: Is the field empty?

if ( [searchText length] == 0 ) {
    // string is empty
}

If you'd prefer not to change FG_Filter, something like this would be a safe change, too:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self FG_Filter:searchText ? searchText : @""];
}
Steven Fisher
Thank you, thats just what I was looking for, excellent answer. Much appreciated.
fuzzygoat
You're welcome. I'm glad I could help! I remember the nil there surprised me, too...
Steven Fisher