iOS开发实现搜索框(UISearchController)

2022-08-08 11:12:22

最近自己在写一个APP,其中需要实现搜索框搜索功能,于是乎就想写篇博客介绍下UISearchController和搜索框的实现。我写的是一个天气预报APP,直接以我APP中的源代码来详细介绍下搜索框的...

最近自己在写一个APP,其中需要实现搜索框搜索功能,于是乎就想写篇博客介绍下UISearchController和搜索框的实现。

我写的是一个天气预报APP,直接以我APP中的源代码来详细介绍下搜索框的实现。

注:在IOS 8.0以上版本中, 我们可以使用UISearandroidchController来非常方便地在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.semUlqQqQoarchBar.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 removeFrhttp://www.cppcns.comomSuperview];
  }
}

效果图如下:

iOS开发实现搜索框(UISearchController)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。