這種方法早就發現了,不過一致沒用,今天拿過來用,發現了一些問題。數組
一、這個東西和表視圖結合使用很方便,首先,建立新的工程,將表視圖控制器做爲工程的根視圖,而且添加一個導航(固然,你能夠不這樣作,可是你的搜索控制器要和表視圖結合使用)atom
二、@interface TableViewController ()<UISearchControllerDelegate,UISearchResultsUpdating>,這裏是要用的兩個代理,spa
三、代理
@property(nonatomic,strong)NSArray *content;//在這裏存放的是你的數據code
@property(nonatomic,strong)NSArray *searchResult;//這個是搜索出來的結果事件
@property(nonatomic,strong)UISearchController *searchController;it
四、在這裏進行代理的設置以及一些屬性(是叫屬性吧)的初始化操做,,,,注意的是,搜索控制器的初始化放在代理的設置以前。io
- (void)viewDidLoad {table
[super viewDidLoad];class
self.content = @[@"beijing",
@"shanghai",
@"guanghzou",
@"shenzhen",
@"huhuhu"
];
self.searchResult = @[];
self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.delegate = self;
[self.searchController.searchBar sizeToFit];
self.tableView.tableHeaderView = self.searchController.searchBar;
}
五、這裏是代理方法的實現(只有這個是必須實現的,就是這個刷新了,這個方法的觸發事件是什麼)
#pragma mark UISearchResultsUpdating
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
if (searchController.searchBar.text.length>0) {
self.searchResult = [self searchByText:searchController.searchBar.text];
}else{
self.searchResult = self.content;
}
[self.tableView reloadData];
}
//將搜索到的結果放到一個數組中返回,這裏是搜索結果的判斷
-(NSArray *)searchByText:(NSString *)text{
NSMutableArray *result = [NSMutableArray array];
for (NSString *str in self.content) {//遍歷你存放全部數據的數組
if ([[str lowercaseString]rangeOfString:[text lowercaseString]].location != NSNotFound) {//這個方法頭一回使用,這個跟NSPredicate有什麼區別
[result addObject:str];
}
}
return result;
}
六、而後就是表視圖的3問1答了
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.searchController.active) {//這裏能夠根據搜索控制器是否是激活狀態來返回不一樣的數值,若是是搜索狀態,表視圖就返回搜索結果的個數個行,若是不在搜索的狀態,就返回全部結果的個數
return self.searchResult.count;
}else{
return self.content.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
if (self.searchController.active) {//這裏的邏輯同返回行數
cell.textLabel.text = self.searchResult[indexPath.row];
}else{
cell.textLabel.text = self.content[indexPath.row];
}
return cell;
}
另外,我該怎麼實現對搜索結果的點擊事件呢。
self.searchController.dimsBackgroundDuringPresentation = NO;
這樣搜索的結果就能夠點擊了,(補充2015-9-22)