简体   繁体   中英

How to add a search bar to the navigation bar

I'd love to add a search bar managed by UISearchController to the right side of my navigation bar.

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    searchController.searchBar.placeholder = "Search"
    searchController.searchBar.searchBarStyle = .Minimal
    searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 200.0, height: 44.0)
    searchController.hidesNavigationBarDuringPresentation = false
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: searchController.searchBar)

When I tap on the search bar (so it becomes active) it covers the whole navigation bar (while overlapping everything else) instead of the little part. How can I fix its frame?

Wrapping the search bar in a UIView seems to do the trick.

    searchController.searchBar.frame = CGRect(x: 0, y: 0, width: 200.0, height: 44.0)
    let barContainer = UIView(frame: searchController.searchBar.frame)
    barContainer.backgroundColor = UIColor.clearColor()
    barContainer.addSubview(searchController.searchBar)
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: barContainer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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