用于tableview的搜索栏

sre*_*rgo 0 uitableview uisearchbar nspredicate ios

我需要为表视图添加一个搜索栏.表包含"名称",它实际上存储在一个名为"patient"的对象内.我有一组"患者"对象.所以要设置一个搜索栏来搜索名称.但是如何使用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;

}
Run Code Online (Sandbox Code Playgroud)

上面是显示表格名称的代码.欢迎任何建议,谢谢

Aks*_*ade 5

要实现搜索功能,请首先查看以下链接 -

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

然后在代码中进行如下更改 -

在.h文件中声明数组 -

NSArray *filteredArray;
Run Code Online (Sandbox Code Playgroud)

In - (void)viewDidLoad方法 -

filteredArray = allPatientDetails;
Run Code Online (Sandbox Code Playgroud)

然后实现UISearchBar委托方法 -

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

并对现有方法进行更改 -

- (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;
}
Run Code Online (Sandbox Code Playgroud)