Home > Uncategorized > Adding SearchBar to filter TableView Data

Adding SearchBar to filter TableView Data

step1: add a searchBar UI element to your tableView and create and outlet for it.

step2: in viewDidLoad (or similar), set the searchBar as self-delegate:

searchBar.delegate=(id)self; 

step3: add a bool variable to your class, I’ve called mine isFiltered

step4: implement the searchBars textDidChange delegate method:

 -(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
  if(text.length == 0) self.isFiltered = FALSE;
  else
  {
    self.isFiltered = true;
    newData = [[NSMutableArray alloc] init];
    NSObject *item;
    for ( item in tableFullDataArray){
    NSRange nameRange = [item.sometextproperty rangeOfString:text options:NSCaseInsensitiveSearch];
    if(nameRange.location != NSNotFound) [newData addObject:item];
   }
  }
  [self.updateTableView reloadData];
}

step5: alter the tableview datasource if isFiltered is True. You must change the rowsInSections, and cellForRowAtIndexPath methods. if isFiltered is true, you want to use the newData array. if not, you want to use your complete data array.
step6: finally, to get rid of the keybaord when user taps on the search button, you must also implement the searchButtonClicked delegate method:

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{</pre>
[self.searchBar resignFirstResponder];

} 

		
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: