2013-10-31 86 views
0

我需要爲表格視圖添加一個搜索欄。表格包含實際存儲在名爲「患者」對象內部的「名稱」。我有一組「患者」對象。 所以要設置一個搜索欄來搜索名稱。但是如何使用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; 

} 

以上是顯示錶格名稱的代碼。 歡迎任何建議,謝謝

+0

http://www.appcoda.com/how-to-add-search-bar-uitableview/ –

+0

謝謝,但我下面的一樣。問題是如何使用NSPredicate來「命名」哪個對象的屬性。我有一個這樣的對象數組。 –

回答

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; 

在 - (無效)viewDidLoad方法 -

filteredArray = allPatientDetails; 

然後實現的UISearchBar委託方法 -

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

,並在現有的方法進行修改 -

- (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; 
} 
+0

非常感謝你:) –

0

很好的nspredicate與自定義對象可以這樣做。

NSPredicate *resultPredicate = [NSPredicate 
           predicateWithFormat:@"SELF.firstName contains[c] %@", 
           searchText]; 


self.searchedMemberNameResults = [self.listedMembers filteredArrayUsingPredicate:resultPredicate]; 

的firstName是一個對象

0

您可以在下面找到用於搜索項目的代碼在故事板的標籤上。它動態搜索;我已經測試過,它正在工作。

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

     NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"job_id contains[c] %@",searchText]; 

     searchResultArray = [responceArray filteredArrayUsingPredicate:resultPredicate]; 

     [jobsTable reloadData]; 
    } 
相關問題