我试图在 UISearchController 中过滤我的搜索栏,但它没有过滤?
@interface TableViewController () <UISearchBarDelegate>
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSMutableArray *searchResults; // Filtered search results
@property (nonatomic, strong) NSMutableArray *objects;
@end
@implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchBar.frame = CGRectMake(0, 0, 0, 44.0);
self.searchController.searchBar.delegate = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
self.searchController.searchBar.barTintColor = [UIColor yellowColor];
self.objects = [@[@"iOS",@"is",@"kool"]mutableCopy];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}
- (void)searchThroughResults
{
NSPredicate *resultsPredicate = [NSPredicate predicateWithFormat:@"SELF contains [search] %@", self.searchController.searchBar.text];
[self.searchResults filteredArrayUsingPredicate:resultsPredicate];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[self searchThroughResults];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
if (tableView == self.tableView) {
return self.objects.count;
} else {
[self searchThroughResults];
return self.searchResults.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
// Configure the cell...
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (tableView == self.tableView) {
cell.textLabel.text = self.objects[indexPath.row];
} else {
cell.textLabel.text = self.searchResults[indexPath.row];
}
return cell;
}
我究竟做错了什么?为什么 tableView 没有被过滤?我还将它发布在:https ://github.com/Kalson/iOS-Study/tree/master/SearchBar