2015-10-17 133 views
2

我觉得这个标题是很自我解释的。我有一个嵌入在导航控制器中的tableView,并希望将一个搜索栏添加到导航栏。我认为iOS 9中关于搜索栏控制器的东西发生了变化,所以请记住,这必须适用于iOS 9.这就是我所拥有的。毫无疑问,这是错误的。将SearchBar添加到NavigationBar Objective-C iOS 9

UISearchController *searchController = [[UISearchController alloc]init]; 
self.searchController.searchBar.barTintColor = [UIColor whiteColor]; 
[self.navigationController addChildViewController:searchController]; 

回答

18

通过故事板添加它。在视图控制器场景中添加搜索栏,如退出并添加第一响应者,然后将导航项的titleView添加到搜索栏。

Check this image for reference

+1

谢谢!现在一直在寻找这个解决方案。 –

+0

正确回答老兄! – kemdo

5
//This method has deprecated in ios 8. So, before ios 8 you can use this. 

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero]; 
[searchBar sizeToFit]; 

UISearchDisplayController *searchDisplayController= [[UISearchDisplayController alloc] initWithSearchBar:searchBar 
            contentsController:self]; 
self.searchDisplayController.searchResultsDelegate = self; 
self.searchDisplayController.searchResultsDataSource = self; 
self.searchDisplayController.delegate = self; 
self.navigationItem.titleView = searchDisplayController.searchBar; 

//对于iOS8上/ ios9使用下面的代码

UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:self]; 
// Use the current view controller to update the search results. 
searchController.searchResultsUpdater = self; 
// Install the search bar as the table header. 
self.navigationItem.titleView = searchController.searchBar; 
// It is usually good to set the presentation context. 
self.definesPresentationContext = YES; 
+0

什么都没有显示出来 –

+0

请出示一个屏幕截图 – Jamil

+0

是你的导航栏显示? – Jamil

0

如果您使用的是UISearchDisplayController,这应该工作。

Apple Docs

searchDisplayController.displaysSearchBarInNavigationBar = true 
+0

UISearchDisplayController在iOS 8中已弃用,因此对于iOS 9而言不是一个好答案。 – Bryan

相关问题