Sumit singh
Sumit singh

Reputation: 2446

How to Add search bar in table view

Actually i have stored too many data in table view and now I want to found my data easily so I need a search bar. Can any one give me a little solution?

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifire = @"CellIdentifire";  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifire];
    }
    cell.textLabel.text = [array objectAtIndex:indexPath.row];
    return cell;
}

Upvotes: 0

Views: 1127

Answers (1)

rptwsthi
rptwsthi

Reputation: 10172

Follow these steps:

  • Drag and drop search bar on table view header
  • Set delegate for search bar to your view controller

Use following code to search:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    //Remove all objects first.
    [self searchTerm:searchText];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"Cancel clicked");
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO];

    [self showAllData];// to show all data
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"Search Clicked");
    [searchBar setShowsCancelButton:NO];
    [searchBar resignFirstResponder];

    [self searchTerm:searchBar.text];
}

-(void)showAllData {
   //load all data in _tableViewDataSourceArray, and reload table
}

-(void)searchTerm : (NSString*)searchText
{
    if (searchText == nil) return;

    _tableViewDataSourceArray = //YOUR SEARCH LOGIC        
    [self.tableView reloadData];
}

Edit: In case you wanna create Search bar with code then, Initialize a search bar and pass it as headerView Of your table view, inside

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

Dont's forget to return height of view in

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

Upvotes: 2

Related Questions