简体   繁体   English

将SearchBar添加到NavigationBar Objective-C iOS 9

[英]Adding SearchBar to NavigationBar Objective-C iOS 9

I think the title is pretty self explanitory. 我认为标题是非常自我解释的。 I have a tableView embedded in a navigation controller and want to add a search bar to the navigation bar. 我有一个嵌入在导航控制器中的tableView,并希望在导航栏中添加一个搜索栏。 I think something changed in iOS 9 regarding searchbar controller things so keep in mind this has to be for iOS 9. This is what i have. 我认为iOS 9中有关于搜索栏控制器的东西发生了变化,所以请记住这必须适用于iOS 9.这就是我所拥有的。 No doubt it is wrong. 毫无疑问,这是错误的。

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

Add it via storyboard. 通过故事板添加它。 Add the search bar in the view controller scene like exit and first responder are added and after that just give the titleView of navigation item to the search bar. 在视图控制器场景中添加搜索栏,例如exit和第一响应者,然后添加导航项的titleView到搜索栏。

查看此图片以供参考

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

// For ios8/ios9 use the following code //对于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;

If you are using a UISearchDisplayController, this should work. 如果您使用的是UISearchDisplayController,这应该可行。

Apple Docs Apple Docs

searchDisplayController.displaysSearchBarInNavigationBar = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM