How to change the size of titleView in navigation bar. Because there's a gap between titleView and backButton in navigationBar

Nguyễn Anh Việt picture Nguyễn Anh Việt · Feb 24, 2017 · Viewed 7.5k times · Source

I've added a search bar to my navigation.titleView

    self.navigationItem.titleView = searchBar

There's also a BackBarButtonItem with title = ""

    self.navigationItem.backBarButtonItem?.title = ""

But then there're gap between Back Button and SearchBar, like this: There're gap between Back Button and SearchBar

I Think that the gap appears here because there's space for title of backBarButtonItem (because my title is null "" but the space still there)

So I want to ask how to omit that gap? I want to make my searchBar nearer my backBarIcon

Thank you so much!

EDIT 1: I try to change searchBar's frame but it's not working

This is my code

    //Change searchBar's frame        
    let titleViewFrame = (searchController.searchBar.frame)
    searchController.searchBar.frame = CGRect(x: titleViewFrame.minX - 20.0, y: titleViewFrame.minY, width: titleViewFrame.width + 20.0, height: titleViewFrame.height)

Answer

Peter Cheng picture Peter Cheng · Feb 24, 2017
override func viewDidLoad() {
    super.viewDidLoad()

    let container = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 22))

    let searchBar = UISearchBar()
    searchBar.translatesAutoresizingMaskIntoConstraints = false
    container.addSubview(searchBar)

    let leftButtonWidth: CGFloat = 35 // left padding
    let rightButtonWidth: CGFloat = 75 // right padding
    let width = view.frame.width - leftButtonWidth - rightButtonWidth
    let offset = (rightButtonWidth - leftButtonWidth) / 2

    NSLayoutConstraint.activate([
        searchBar.topAnchor.constraint(equalTo: container.topAnchor),
        searchBar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
        searchBar.centerXAnchor.constraint(equalTo: container.centerXAnchor, constant: -offset),
        searchBar.widthAnchor.constraint(equalToConstant: width)
    ])


    self.navigationItem.titleView = container
}

enter image description here