Search code examples
iosswiftuinavigationbaruisearchbaruinavigationitem

UISearchBar in iOS 8 - UI displacement


I have UINavigationItem and I want to add UISearchBar to it. Here's how I'm doing that:

let searchBar = UISearchBar(frame: CGRectMake(0, 0, self.navigationController!.navigationBar.bounds.width, self.navigationController!.navigationBar.bounds.height))
//searchBar.sizeToFit()
searchBar.showsCancelButton = true
let barWrapper = UIView(frame: searchBar.frame)
barWrapper.addSubview(searchBar)
self.navigationItem.titleView = barWrapper

Here's result:enter image description here

What's wrong here?


Solution

  • sizeToFit() will make the UIScrollView just big enough to fit its subviews.

    You need to size it to fit the navigation bar to get rid of the gaps.

    EDIT

    If you're not using the nav bar for navigation, try just putting the search bar directly in your view. You'll have full control over the frame that way.