将SearchBar添加到NavigationBar Objective-C iOS 9

4

我认为标题已经很明确了。我有一个嵌入导航控制器的tableView,并想在导航栏中添加搜索栏。我认为iOS 9中关于搜索栏控制器的东西发生了一些变化,请记住这必须是针对iOS 9的。这就是我拥有的。毫无疑问,它是错误的。

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

25

通过storyboard添加。在视图控制器场景中添加搜索栏,就像添加退出和第一响应者一样,然后只需将导航项的titleView设置为搜索栏。

参考此图像


1
谢谢!我已经寻找这个解决方案有一段时间了。 - Paul Lehn
你是个救星兄弟 :) - Ankit Kumar Gupta

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

让我们在聊天中继续这个讨论 - Jamil

0
如果您正在使用UISearchDisplayController,这应该可以工作。 Apple Docs
searchDisplayController.displaysSearchBarInNavigationBar = true

2
UISearchDisplayController在iOS 8中已被弃用,因此不适用于iOS 9。 - Bryan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接