Reputation: 29
I've created a UISearchbar
with a cancel button, but when I click on the cancel button, it does not show the array and it just dismisses the keyboard.
allItems
is NSArray
and
displayItems
is NSMutableArray
-(void)searchBarSearchButtonClicked:(UISearchBar *)asearchBar{
[displayItems addObject:allItems];
[searchBar resignFirstResponder];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if ([searchText length] == 0) {
[displayItems removeAllObjects];
[displayItems addObjectsFromArray:allItems];
} else {
[displayItems removeAllObjects];
for (NSString * string in allItems ){
NSRange r =[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (r.location != NSNotFound){
[displayItems addObject:string];
}
}
[tableView reloadData];
}
}
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellAccessoryDisclosureIndicator;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)asearchBar{
[displayItems removeAllObjects];
[displayItems addObjectsFromArray:allItems];
[searchBar resignFirstResponder];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)asearchBar{
[searchBar resignFirstResponder];
}
Upvotes: 1
Views: 1586
Reputation: 14427
You really ought to be using two Arrays for this. One an NSArray called something like originalData and the other an NSMutableArray called filteredData. These will both be the same in the beginning and when filtering, you will build/rebuild the filteredData array from the originalData array. Here is a rough example:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if ([searchText length]) {
[displayItems removeAllObjects];
for (NSString * string in allItems ){
NSRange r =[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (r.location != NSNotFound){
[displayItems addObject:string];
}
[tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}
}
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)asearchBar{
[searchBar resignFirstResponder];
self.displayItems = [[NSMutableArray alloc] initWithArray:allItems];
[tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
}
I also add a delegate method for the ScrollView
(TableView
) so that when scrolling starts, the keyboard gets dismissed:
#pragma mark - ScrollView (UITableView) delegate methods
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[mySearchBar resignFirstResponder];
}
Upvotes: 1