2

I am trying to add two buttons and a SearchBar to my navigation controller but the alignment is not correct. I have tried almost everything such as changing the size of SearchBar, UIButton or changing the Y positioning but it didn't work. Any idea how to fix this issue? enter image description here I am using iOS 11 and Xcode 9

    searchController = UISearchController(searchResultsController: nil)
    searchController?.searchBar.frame = CGRect(x: 0, y: 0, width: 200, height: 30)
    searchController?.delegate = self
    searchController?.searchResultsUpdater = self

    let refineButton = UIButton.init(type: UIButtonType.custom)
    refineButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    refineButton.setImage(#imageLiteral(resourceName: "settings-button"), for: UIControlState.normal)
    refineButton.widthAnchor.constraint(equalToConstant: 30).isActive = true
    refineButton.heightAnchor.constraint(equalToConstant: 30).isActive = true


    let refineItem = UIBarButtonItem(customView: refineButton)


    navigationItem.leftBarButtonItem = refineItem
    navigationItem.titleView = searchController?.searchBar
    searchController?.searchBar.sizeToFit()
Persian
  • 294
  • 2
  • 10
  • 1
    I'm not sure if this will help but why not use `navigationItem.searchController = searchController` instead of `navigationItem.titleView = searchController?.searchBar`. Of course that only works with iOS 11. – rmaddy Sep 23 '17 at 22:31
  • 1
    @rmaddy unfortunately that wouldn't work as the search controller will go below the buttons – Siyavash Sep 23 '17 at 23:23

1 Answers1

0

Please check :

override func viewWillLayoutSubviews() {
    searchController?.searchBar.frame = CGRect(x: 0, y: 0, width: 300, height: 30)
    searchController?.searchBar.sizeToFit()
}
Vini App
  • 7,339
  • 2
  • 26
  • 43