我一直想知道如何针对这种情况实施最佳实践。
我有一个UITableViewController,并且想要以编程方式添加searchBar,所以我在viewForHeaderInSection上执行了此操作
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 44)];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 44)];
searchBar.placeholder = @"Search";
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchBar.delegate=self;
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate = self; //This one keep messing with the layout
[view setBackgroundColor:[UIColor blackColor]];
[view addSubview:searchBar];
return view;
}
注释行引起了我的searchBar编辑时的奇怪位置和行为,如下图所示。
第一响应者使状态栏重叠,尽管我在viewDidLoad上添加了
self.edgesForExtendedLayout = UIRectEdgeNone;
如果我删除了searchDisplayController.searchResultsDelegate = self; 所有视图看起来都很完美,但是我需要这个委托来在searchResultTableView上触发didSelectedRow。这怎么可能?在这种情况下最好的方法是什么?谢谢!
更新
当我在各处搜索时,借助于给出的答案,我可以得出结论,如果要在UITableView上修复SearchBar,只需在UIViewController上创建tableview,放置searchBar,放置一些约束,然后瞧!
不要在viewForHeaderInSection中创建您的searchController,而是为您的viewController创建一个searchController变量,如下所示:
let searchController = UISearchController(searchResultsController: nil)
然后使用此函数对其进行配置,并在viewDidLoad中调用此函数:
func configureSearchController() {
searchController.searchBar.delegate = self
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.barTintColor = UIColor.whiteColor()
searchController.searchBar.tintColor = UIColor.blackColor()
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
物镜
这是有关如何在Objective-C中完成此操作的重要链接:如何使用目标C实现UISearchController
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句