Search code examples
iosobjective-cuitableviewuisearchbaruisearchdisplaycontroller

How do I use the UISearchBar and UISearchDisplayController


I have an app which displays quite a lot of data in a UITableView. I already added the UISearchBar and UISearchDisplayController in Interface Builder to the UITableView. But I do not know how to use it. If someone could provide a quick solution to this, I would be grateful. I just require it to work as you type to find matches of the search query in the UITableView cells (or from an array).

UPDATE 1: Here's the code from thenumberOfRowsInSection method:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
{  
if (isSearching) {  
        return [searchResults count];  
    }  
    else {  
        if (section == 0) {  
            return 1;  
        }  
        else if (section == 1) {  
            return [basicQuantities count];  
        }  
        else if (section == 2) {  
            return [physicalQuantities count];  
        }  
    }  

    return nil;  
}

Solution

    • First add the UISearchDisplayController to your table view
    • Then set its delegate.
    • Implement the following methods.

    Demo Project

    In your .h File

        @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    
        NSMutableArray *contentList;
        NSMutableArray *filteredContentList;
        BOOL isSearching;
    }
    @property (strong, nonatomic) IBOutlet UITableView *tblContentList;
    @property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
    @property (strong, nonatomic) IBOutlet UISearchDisplayController *searchBarController;
    

    In your .m File

    Filling the sample data (Optional Only For Demo Purpose)

    - (void)viewDidLoad {
        [super viewDidLoad];
        contentList = [[NSMutableArray alloc] initWithObjects:@"iPhone", @"iPod", @"iPod touch", @"iMac", @"Mac Pro", @"iBook",@"MacBook", @"MacBook Pro", @"PowerBook", nil];
        filteredContentList = [[NSMutableArray alloc] init];
    }
    

    Now implement the Table View Delegate and Datasource

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
        // Return the number of sections.
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        // Return the number of rows in the section.
        if (isSearching) {
            return [filteredContentList count];
        }
        else {
            return [contentList count];
        }
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier = @"Cell";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
    
        // Configure the cell...
        if (isSearching) {
            cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
        }
        else {
            cell.textLabel.text = [contentList objectAtIndex:indexPath.row];
        }
        return cell;
    
    }
    

    Search Function Responsible For Searching

    - (void)searchTableList {
        NSString *searchString = searchBar.text;
    
        for (NSString *tempStr in contentList) {
            NSComparisonResult result = [tempStr compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
            if (result == NSOrderedSame) {
                [filteredContentList addObject:tempStr];
            }
        }
    }
    

    Search Bar Implementation

    - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
        isSearching = YES;
    }
    
    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
        NSLog(@"Text change - %d",isSearching);
    
        //Remove all objects first.
        [filteredContentList removeAllObjects];
    
        if([searchText length] != 0) {
            isSearching = YES;
            [self searchTableList];
        }
        else {
            isSearching = NO;
        }
        // [self.tblContentList reloadData];
    }
    
    - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
        NSLog(@"Cancel clicked");
    }
    
    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
        NSLog(@"Search Clicked");
        [self searchTableList];
    }