sreejith.virgo sreejith.virgo - 4 months ago 13
iOS Question

search bar for tableview

I need to add a search bar for a table view.Table contain "Names" which is actually stored in inside an object called "patient".I have an array of "patient" objects.
So to setup a search bar to search for names.But how to do it using NSPredicate?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* CellId= @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId] ;
}
cell.accessoryType = UITableViewCellAccessoryNone;

ObjPatient = [allPatientDetails objectAtIndex:indexPath.row];
cell.textLabel.text =[NSString stringWithFormat:@"%@ %@",ObjPatient.firstName,ObjPatient.lastName];
return cell;

}


Above is the code to show the names on table.
Any suggestions are welcome , Thanks

Answer

To Implement search functionality first take look into below links -

https://developer.apple.com/library/ios/documentation/uikit/reference/UISearchBar_Class/Reference.html https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/Reference/NSPredicate.html

Then make changes in your code as follows -

In your .h file declare array -

NSArray *filteredArray;

In - (void)viewDidLoad method -

filteredArray = allPatientDetails;

Then implement UISearchBar delegate method-

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSPredicate *predicate = [NSPredicate
                            predicateWithFormat:@"SELF.firstName contains[c] %@",
                            searchText];
    NSArray *filteredArray = [allPatientDetails filteredArrayUsingPredicate:predicate];
   [tableView reloadData];
}

and make changes in your existing method -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString* identifier= @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    if (!cell) {
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] ;

    }
    cell.accessoryType = UITableViewCellAccessoryNone;

    ObjPatient = [filteredArray objectAtIndex:indexPath.row];
    cell.textLabel.text =[NSString stringWithFormat:@"%@ %@",ObjPatient.firstName,ObjPatient.lastName];
    return cell;
}