iOS - UISearchController

1.UISearchBar添加在Searchview中,searchController要对应一个viewController。

    BookSearchController *searchController = [self.storyboard instantiateViewControllerWithIdentifier:@"BookSearchController"];
    searchController.bookViewController = self;
    [self.searchView addSubview:searchController.
     searchController.searchBar];

这里写图片描述

2.BookSearchController要实现

3.创建searchController,设置数据更新器,删除底图,背景透明

- (void)awakeFromNib {

    searchTitles = [NSArray array];

    //显示ui是这个
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:self];
    //数据更新也是这个
    self.searchController.searchResultsUpdater = self;

    self.searchController.searchBar.placeholder = @"搜索图书";
    self.searchController.searchBar.tintColor = [UIColor whiteColor];

    //UISearchController原本有底图,删除
    [self.searchController.searchBar.subviews[0].subviews[0] removeFromSuperview];

}

4.实现数据更新器的协议,搜索文字更改都会触发这个方法

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    NSString *tag = [searchController.searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (![tag isEqualToString:@""] || !tag) {
        [NetworkManager getBookTitlesWithTag:tag
                                        page:0
                               resultClosure:^(NSArray * titles) {
                                   searchTitles = titles;
                                   [self.tableView reloadData];
                               }];
    }
}

5.实现tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return searchTitles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    cell.textLabel.text = searchTitles[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.searchController.active = NO;
    self.bookViewController.tag = searchTitles[indexPath.row];
    [self.bookViewController.tableView.mj_header beginRefreshing];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值