亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

iOS開發(fā)實現(xiàn)搜索框(UISearchController)

 更新時間:2022年08月08日 10:54:01   作者:中二小葦  
這篇文章主要為大家詳細介紹了iOS開發(fā)實現(xiàn)搜索框,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

最近自己在寫一個APP,其中需要實現(xiàn)搜索框搜索功能,于是乎就想寫篇博客介紹下UISearchController和搜索框的實現(xiàn)。

我寫的是一個天氣預(yù)報APP,直接以我APP中的源代碼來詳細介紹下搜索框的實現(xiàn)。

注:在iOS 8.0以上版本中, 我們可以使用UISearchController來非常方便地在UITableView中添加搜索框. 而在之前版本中, 我們還是必須使用UISearchBar + UISearchDisplayController的組合方式。

初始化UISearchController

- (void)viewDidLoad {
? ? [super viewDidLoad];

? ? self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
? ? self.searchController.searchResultsUpdater = self;
? ? self.searchController.dimsBackgroundDuringPresentation = false;
? ? [self.searchController.searchBar sizeToFit];
? ? self.tableView.tableHeaderView = self.searchController.searchBar;

}

使用UISearchController要繼承UISearchResultsUpdating協(xié)議, 搜索必須實現(xiàn)UISearchResultsUpdating方法.

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
? ? [self.searchList removeAllObjects];
? ? //在iOS開發(fā)中,系統(tǒng)提供了NSPredicate這個類給我們進行一些匹配、篩選操作
? ? NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", self.searchController.searchBar.text];
? ? self.searchList = [[self.dataList filteredArrayUsingPredicate:searchPredicate] mutableCopy];
? ? dispatch_async(dispatch_get_main_queue(), ^{
? ? ? ? [self.tableView reloadData];
? ? });
}

通過UISearchController的active屬性來判斷輸入框是否處于active狀態(tài),然后更新UITableview

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

? ? return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

? ? if (!self.searchController.active) {
? ? ? ? return self.dataList.count;
? ? }
? ? else{
? ? ? ? return self.searchList.count;
? ? }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
? ? static NSString *ID = @"cell";
? ? UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
? ? if (!cell) {
? ? ? ? cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
? ? }
? ? if (!self.searchController.active) {
? ? ? ? cell.textLabel.text = self.dataList[indexPath.row];
? ? }
? ? else{
? ? ? ? cell.textLabel.text = self.searchList[indexPath.row];
? ? }
? ? return cell;

}

搜索完之后,將搜索框移除

- (void)viewWillDisappear:(BOOL)animated {
? ? [super viewWillDisappear:animated];
? ? if (self.searchController.active) {
? ? ? ? self.searchController.active = NO;
? ? ? ? [self.searchController.searchBar removeFromSuperview];
? ? }
}

效果圖如下:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論