2

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?

David
  • 125
  • 2
  • 15
  • 1
    Have you tried to drag & drop a `UIView` from the Object library to your navigation bar, and then drag & drop the `UISearchController` into that UIView? ...I haven't tried is so I'm not sure if it should work. – Andrej Aug 29 '16 at 17:57
  • UISearchController is not available in the Object Palette. But wrapping the search bar inside UIView seems to be a good idea, let me check that out. – David Aug 29 '16 at 19:04
  • Great, wrapping search bar in a UIView does the trick. Thank you :) – David Aug 29 '16 at 19:07

1 Answers1

3

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)
David
  • 125
  • 2
  • 15