SwiftUI - Missing Toolbar Button

195 Views Asked by At

The following sample code illustrates an issue I am having with my SwiftUI app:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("Hello, world!")
                .toolbar {
                    ToolbarItem {
                        Button {
                            print("house")
                        } label: { Image(systemName: "house") }
                    }
                    
                    ToolbarItem {
                        Button {
                            print("bookmark")
                        } label: { Image(systemName: "bookmark") }
                    }
                }
        } //NavigationView
    } //body
}

When I run this on an iPhone 13 simulator running iOS 16+, it works fine. But, on an iPhone 13 simulator running iOS 15.0, only the first toolbar button appears -- the "bookmark" button does not appear. I would appreciate any suggestions as to what I'm missing!

2

There are 2 best solutions below

0
On

Solved by replacing ToolbarItems with HStack:

        .toolbar {
            HStack {
                Button {
                    print("house")
                } label: { Image(systemName: "house") }
                
                Button {
                    print("bookmark")
                } label: { Image(systemName: "bookmark") }
            } //HStack
        }
1
On

I'd suggest using a ToolbarItemGroup for this, eg.

      .toolbar {
                ToolbarItemGroup(placement: .primaryAction){
                    Button {
                        print("house")
                    } label: { Image(systemName: "house") }
                    
                    Button {
                        print("bookmark")
                    } label: { Image(systemName: "bookmark") }
                }
            }

Although your HStack workaround will work, it might be more brittle to platform-specific changes, and the (optional) placement parameter lets you be explicit about where you want the buttons to appear.