日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

iOS開發實現搜索框(UISearchController)_IOS

作者:中二小葦 ? 更新時間: 2022-10-02 編程語言

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

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

注:在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協議, 搜索必須實現UISearchResultsUpdating方法.

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
? ? [self.searchList removeAllObjects];
? ? //在iOS開發中,系統提供了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狀態,然后更新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];
? ? }
}

效果圖如下:

原文鏈接:https://ahtchxw.blog.csdn.net/article/details/51581697

欄目分類
最近更新