将搜索栏添加到导航栏 Objective-C iOS 9

Adding SearchBar to NavigationBar Objective-C iOS 9

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

 UISearchController *searchController = [[UISearchController alloc]init];
self.searchController.searchBar.barTintColor = [UIColor whiteColor];
[self.navigationController addChildViewController:searchController];
//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,这应该可以。

Apple Docs

searchDisplayController.displaysSearchBarInNavigationBar = true

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