SwiftUI `navigationBarItems` vs `toolbar` what are the differences?

Viewed 2615

What are the differences between navigationBarItems vs toolbar in SwiftUI? I've been using them interchangeably and feel like they are doing the same things with different syntax, eg: put buttons on navigationBar (.leading/.trailing).

3 Answers

As mentioned by Lorem Ipsum, .toolbar is the way to go forward. The biggest difference is that .navigationBarItems is iOS/iPad OS only, whereas .toolbar works on macOS as well.

This makes it much easier to create universal views.

If you're just targeting mobile devices, there isn't really any difference in outcome at the moment.

.toolbar will (by default) automatically display the button on the leading or trailing edge depending on the locale.

.toolbar(
    Button("Edit") {
        print("Editing ...")
    }
)

This will show the button on the trailing edge for left- to-right languages, or on the leading edge for right-to-left. You can put it where you want by wrapping it in a ToolbarItem().

.toolbar(
    ToolbarItem(placement: .navigationBarLeading) {
        // Button
    }
)

In addition to what has been said: .toolbar requires iOS 14. A lots of projects need to be backward-compatible to iOS 13 and then navigationBarItems is the only way to achieve this

Related