Alessandro
Alessandro

Reputation: 4110

Search TableView with UISearchBar

I have a search bar added in the user interface. The Searchbar is already set, and works, but I can't figure out how to make it search content in the UITableView. Can I just remove the items that do not start with the characters typed in the search bar??

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
if (searchBar.text.length < 1) {
    return;
}
else {
    // Do search stuff here



}}

This code works, the else function is called. But I don't know how to do it. I don't want to create a whole new array just for that.

Upvotes: 1

Views: 920

Answers (1)

CodaFi
CodaFi

Reputation: 43330

I'll do you one better. This example will search as the user types. If your data is quite massive, you may want to implement it in - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar like you originally planned. Unfortunately, you need a second array, but it's easy to code around it in the table:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if(searchText.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {

        isFiltered = true;
        if (filteredTableData == nil)
            filteredTableData = [[NSMutableArray alloc] init];
        else 
            [filteredTableData removeAllObjects];

        for (NSString* string in self.masterSiteList)
        {
            NSRange nameRange = [string rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
            if(nameRange.location != NSNotFound)
            {
                [filteredTableData addObject:string];
            }
        }
    }
    [self.tableView reloadData];
}

then update your delegate methods to show the data of the filteredTableData array instead of the regular array when the isFiltered var is set to YES.

Upvotes: 3

Related Questions