Displaying search bar in navigation bar in iOS 8

☆樱花仙子☆ 提交于 2019-11-27 03:21:10
Victor Sigler

According to Apple :

UISearchDisplayController is deprecated in iOS 8. (Note that UISearchDisplayDelegate is also deprecated.) To manage the presentation of a search bar and display search results in iOS 8 and later, instead use UISearchController.

The UISearchController class defines an interface that manages the presentation of a search bar in concert with the search results controller’s content. The search results controller, a UIViewController object specified by the searchResultsController property, manages the results of the search.

Now you can use the UISearchController to show the search bar in your navigation bar in the following way:

class ViewController: UIViewController, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {

    var searchController : UISearchController!

    override func viewDidLoad() {
       super.viewDidLoad()

       self.searchController = UISearchController(searchResultsController:  nil)

       self.searchController.searchResultsUpdater = self
       self.searchController.delegate = self
       self.searchController.searchBar.delegate = self

       self.searchController.hidesNavigationBarDuringPresentation = false
       self.searchController.dimsBackgroundDuringPresentation = true

       self.navigationItem.titleView = searchController.searchBar

       self.definesPresentationContext = true        
    }

    func updateSearchResults(for searchController: UISearchController) {

    }

    override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
       // Dispose of any resources that can be recreated.
    }
}

But you have to consider you need to set a UINavigationController like in this Storyboard :

You can do it very easy just select your ViewController and see the following steps:

And then you should see in your device when you make click in the search bar the following picture:

I hope this help you

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!