Search code examples
swiftuinavigationcontrolleruinavigationbar

How to stretch title view in swift?


I created custom title view for UINavigationItem.
And I want custom view stretch to right padding.
What can I do??

I tried to set rightBarButtonItem to nil.
But it seems no solution.
And don't stretch to left backButton area.

override func viewDidLoad() {
    super.viewDidLoad()

    let searchBar = CustomSearchBar()
    searchBar.autoresizingMask = .flexibleWidth
    searchBar.frame = CGRect(x: 0, y: 0, width: 400, height: 30)

    self.navigationItem.titleView = searchBar

    self.navigationItem.rightBarButtonItem = UIBarButtonItem()
}

See my result. I want a red area.

https://i.sstatic.net/n6owW.jpg


Solution

  • Try the following inside your CustomSearchBar class:

    override var intrinsicContentSize: CGSize {
        return UILayoutFittingExpandedSize
    }