Adding SearchBar to NavigationBar Objective-C iOS

2019-05-03 11:43发布

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. 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. No doubt it is wrong.

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

3条回答
Evening l夕情丶
2楼-- · 2019-05-03 11:53
//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

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;
查看更多
叛逆
3楼-- · 2019-05-03 11:53

If you are using a UISearchDisplayController, this should work.

Apple Docs

searchDisplayController.displaysSearchBarInNavigationBar = true
查看更多
做个烂人
4楼-- · 2019-05-03 12:03

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.

Check this image for reference

查看更多
登录 后发表回答