Created
December 4, 2014 16:31
-
-
Save lborsato/d52ca5e286111f84fcf5 to your computer and use it in GitHub Desktop.
iOS SearchBar Delegate code in Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma mark - SearchBar delegate methods | |
- (void) doSearch:(NSString *)searchText { | |
[self.filteredEntries removeAllObjects]; | |
if ( [searchText length] == 0 ) { | |
[self.filteredEntries addObjectsFromArray:self.entries]; | |
} else { | |
for (NSDictionary *entry in self.entries) { | |
NSString *name = (NSString *)[entry objectForKey:@"fullName"]; | |
NSRange range = [[name lowercaseString] rangeOfString:[searchText lowercaseString]]; | |
if ( range.location != NSNotFound ) | |
[self.filteredEntries addObject:entry]; | |
} | |
} | |
[self.tableView reloadData]; | |
} | |
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { | |
if ( [searchText length] > 0 ) | |
{ | |
[self showCancelButton:YES]; | |
} | |
else { | |
[self showCancelButton:NO]; | |
[searchBar resignFirstResponder]; | |
} | |
[self doSearch:searchText]; | |
} | |
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar | |
{ | |
[self showCancelButton:YES]; | |
} | |
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar | |
{ | |
if ( [searchBar.text length] > 0 ) [self showCancelButton:YES]; | |
else [self showCancelButton:NO]; | |
[self doSearch:_searchBar.text]; | |
} | |
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar | |
{ | |
[searchBar resignFirstResponder]; | |
[self showCancelButton:NO]; | |
} | |
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar | |
{ | |
[searchBar resignFirstResponder]; | |
searchBar.text = @""; | |
[self showCancelButton:NO]; | |
[self.filteredEntries removeAllObjects]; | |
[self.filteredEntries addObjectsFromArray:self.entries]; | |
[self.tableView reloadData]; | |
[[UIApplication sharedApplication] setStatusBarHidden:YES]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment