Can I use a UISearchController with a storyboard?

2019-08-03 18:43发布

问题:

Is there a way to use UISearchController in a way that lets me storyboard the UISearchBar? I have a storyboarded UI with a navigation bar which contains my search bar. It would be great if I could keep it this way because setting up the layout programmatically would be really inconvenient. I know the old UISearchDisplayController could be storyboarded. Is there a way to do something similar with UISearchController?

回答1:

Add a UIView to your layout. That will be the container for your UISearchBar. Then programmatically instantiate the UISearchController and then add the searchbar to the container:

let searchController = UISearchController(searchResultsController: searchResultsController)
searchBarContainer.addSubview(searchController.searchBar)


回答2:

No, unfortunately that is not possible yet (iOS 10 and before). See this example code which was updated for iOS 10 that shows how to setup the UISearchController programmatically.