2015-10-17 134 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

相關問題