SwiftUI ToolbarItemGroup(placement: .principal) makes dynamic content unresponsive

Viewed 24

I have a SwiftUI view like follows:

struct ContentView: View {
    
    @State private var showButton2 = false
    
    var body: some View {
        NavigationView {
            Button("show button2") {
                showButton2.toggle()
            }
            .toolbar {
                ToolbarItemGroup(placement: .principal) {
                    HStack {
                        Button("button1") {
                            print("button1 pressed")
                        }
                        
                        if showButton2 {
                            Button("button2") {
                                print("button2 pressed")
                            }
                        }
                    }
                }
            }
        }
    }
}

With this I want to achieve dynamic .toolbar buttons.

Button1 works perfectly before showing button2. After button2 is presented, button1 doesn't respond well to touches anymore. Button2 on the other hand works fine.

If I change the placement to anything else (e.g. navigationBarLeading) the code works as expected and button1 is responsive.

Does anyone know why button1 isn't responding well to touches anymore and how to fix that?

1 Answers

If you look at the view hierarchy you see that that the buttons are cut off, the visible portions still work as expected.

That is because the size of the .principal does not seem to change its size dynamically but still only takes the initial size, in your case just the size of one button.

You could force the view to take as much space as possible with .frame(maxWidth: .infinity) added to your HStack

enter image description here

Related