In an app that is based on a UINavigationController, the navigation controller's toolbar is turned on so that there is the UINavigationBar at the top and the UIToolbar at the bottom.
For the root view controller there is obviously no back button, and there is also no title (and no title view). I have set the title = nil
.
This same root view controller has a lot of bar button items in the navigation bar's rightBarButtonItems
. Since there is nothing else in the navigation bar apart from these items, I would like them to be centred and evenly spaced across the navigation bar. This way, they would look less crowded, be less likely to touch the wrong button, looks nicer in general, and would also match the look of the toolbar at the bottom.
In the bottom toolbar, this is easily achieved by using flexible space between each item (and before/after the first/last items in my case).
For the top navigation bar, flexible spaces (and fixed spaces) appears to be ignored.
How can I get my bar button items in the navigation bar to spread out across the entire bar when there is nothing else on the bar?
Or is the only option to hide the bar, and actually place an independent toolbar at the top in its place? (Would be a shame to have to resort to this, as the nav bar is already there and very nearly doing the job and is automatically managed.)
I've found an even simpler way to achieve this now.
This version simply divides the available space between the number of items.
Subtracting 2 points seems to work better - without this the results are not as pleasing in a crowded toolbar. I guess this allows for a tiny margin between each item?
Note that if the text/image of some items is wider than other items, then the spacing between each will not be even. So this method is best suited to items that have similar widths.
func updateNavbarItemSpacing(forBarWidth barWidth: CGFloat) {
guard let items = navigationItem.leftBarButtonItems else { return }
if items.count == 0 { return }
let itemWidth = barWidth / CGFloat(items.count) - 2
for item in items {
item.width = itemWidth
}
navigationItem.leftBarButtonItems = items
}
Call the above after setting the navigationItem's left toobar items.
Also, for correct behaviour when rotating the device, call it in the view controller's:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
updateNavbarItemSpacing(forBarWidth: size.width)
}