将SearchBar添加到NavigationBar Objective-C iOS 9

我认为这个标题是非常自我解释的。 我有一个embedded在导航控制器中的tableView,并希望将一个search栏添加到导航栏。 我想在iOS 9中关于search栏控制器的东西发生了变化,所以请记住,这一定是针对iOS 9的。这就是我所拥有的。 毫无疑问,这是错误的。

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

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

检查这个图像作为参考

 //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; 

如果你正在使用UISearchDisplayController,这应该工作。

苹果文件

 searchDisplayController.displaysSearchBarInNavigationBar = true