【发布时间】:2016-02-14 09:21:23
【问题描述】:
我正在尝试添加搜索栏来搜索我的 tableView。只有一个 TableViewController 添加了 searchBar。我检查了所有现有指南和苹果示例代码并按照说明进行操作,但不知何故我的 tableView 在输入搜索字符串后没有重新加载。我用 NSLog 检查了我的代码,我确定搜索文本已正确上传,并且使用 NSPredicate 过滤了新数组。我在“updateSearchResultsForSearchController:”方法的末尾添加了 [self.tableView reloadData],但仍然是我的tableViewController 未更新。我是 iOS 编程新手,不知道我做错了什么。感谢您是否可以快速浏览我的代码并向我提供反馈。总结如下:
@property (nonatomic,strong) UISearchController *searchController;
@property (nonatomic,strong) NSArray *myList; //original data list
@property (nonatomic,strong) NSArray *mysearchResult; //filtered list
- (void)viewDidLoad {
[super viewDidLoad];
self.searchController=[[UISearchController alloc]initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater=self;
self.searchController.dimsBackgroundDuringPresentation=NO;
self.searchController.searchBar.delegate=self;
self.tableView.tableHeaderView=self.searchController.searchBar;
self.definesPresentationContext=YES;
[self.searchController.searchBar sizeToFit];
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *searchString=self.searchController.searchBar.text;
NSPredicate *mypredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@", searchString];
self.mysearchResult=[self.myList filteredArrayUsingPredicate:mypredicate];
[self.tableView reloadData];
}
tableView代码的“CellForRowAtIndexPath”方法:(类似“numberOfRowsInSection”更新)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCell codes.....
if (tableView==self.tableView) {
cell.cellLabel.text=[self.myList objectAtIndex:indexPath.row];
} else
cell.cellLabel.text=[self.mysearchResult objectAtIndex:indexPath.row];
return cell;
}
【问题讨论】:
-
你分配了tabeView的dataSource和delegate吗?
-
你只有一个TableView吗?如果是这样,您的 if 条件将始终为真。并且您的数据总是从 self.myList 加载。解决方案如下。
标签: objective-c ios9 reloaddata uisearchcontroller