Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add searchbar in uitableview?

I have an NSMutableArray displayed in a UITableView, and I have added some elements there.

For example, element names are First, FirstTwo, Second, SecondTwo, Third, ThirdTwo.

Now I want to add a search bar in the screen. In that search bar when I type F, the table should only show First and FirstTwo.

How should I do this?

like image 976
Jean-Luc Godard Avatar asked Apr 04 '11 12:04

Jean-Luc Godard


2 Answers

 searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

 searchBar.delegate = self;

 self.tableView.tableHeaderView = searchBar;
like image 124
SachinVsSachin Avatar answered Sep 19 '22 21:09

SachinVsSachin


The best way to get the hang of this is by following a tutorial over here over here. The part you are looking for, is this:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
   [tableData removeAllObjects];// remove all data that belongs to previous search
   if([searchText isEqualToString:@""]searchText==nil){
      [myTableView reloadData];
      return;
   }

   NSInteger counter = 0;
   for(NSString *name in dataSource)
   {
      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
      NSRange r = [name rangeOfString:searchText];
      if(r.location != NSNotFound)
      {
         if(r.location== 0)//that is we are checking only the start of the names.
         {
            [tableData addObject:name];
         }
      }

      counter++;
      [pool release];

   }

   [myTableView reloadData];
}
like image 22
Joetjah Avatar answered Sep 19 '22 21:09

Joetjah