先把代码贴出来,设置UISearchController的SerachBar为UITableView的HeaderView,核心代码如下:
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
_tableView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_tableView];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.tableView.tableHeaderView = self.searchController.searchBar;
这样即可正常显示。
注意设置:self.searchController.hidesNavigationBarDuringPresentation = YES; //这个默认是yes的。
坑:如果我们在ViewController中设置了self.edgesForExtendedLayout = UIRectEdgeNone; 会出现表格的一部分被searchBar给盖住,也就是cell向上移动了