I am using the large title navbar with iOS 11, but when I add a bar button item it looks weird positioned in the same location as the original title navbar. I would like to move the bar button item down when the title is large, and move it back into its original position when the navbar is no longer large. What would be the best way of doing this?
This is an image showing the weird position of the bar button item
I can get the navbar height dynamically using the viewWillLayoutSubviews(), but I can't change the position of the bar button item using setTitlePositionAdjustment
override func viewWillLayoutSubviews() {
guard let navbarHeight = self.navigationController?.navigationBar.frame.height else{ return }
}
What you want to do is set the title position adjustments of the
BarButtonItem
. Add the following line to theviewWillAppear
func. Play with thevertical
andhorizontal
value to get thelayout
of ur liking.navigationItem.rightBarButtonItem?.setTitlePositionAdjustment(.init(horizontal: 10, vertical: 20), for: UIBarMetrics.default)
https://developer.apple.com/documentation/uikit/uibarbuttonitem/1617149-settitlepositionadjustment
Updated Answer If you want to adjust button below the title if it grows then in this case you need to load the custom view on your navigation bar.
To solve my own problem, I just added a button as a subview of the navbar and set the right and bottom constraints to the navbar. The button will now move up and down when the navbar changes size. However, this requires the button to be removed in any view controllers that you show segue from this view controller. Thus, I added a tag of 1 to the button and removed it from its superview from the other view controller. This is the easiest way to solve it, and I found it the easiest method.
To setup the right button:
To remove it from any show segued view controllers:
Both functions are called in the viewWillAppear function