Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird toolbar with nested conditionals behavior

I'm getting this extremely odd issue where if you have a deep chain of ViewBuilder's and if statements, along with a toolbar, some of the items in the toolbar duplicate.

Here is an image to show what I mean (Notice the 2 "Press me!" buttons)

screenshot)

Reproduction: (Note: I'm using macOS Monterey Beta 5 and Xcode 13 Beta 5)

  1. Create a new blank SwiftUI macOS project
  2. Paste this code into ContentView:
struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("Sidebar")
            SecondPanel()
        }
    }
}
struct SecondPanel: View {
    @State var num = 0
    
    @ViewBuilder var content: some View {
        Text("Line 2")
        Text("Line 3")
    }
    @ViewBuilder var contentWithToolbar: some View {
        content
            .toolbar {
                Button(action: {
                    num += 1
                }) {
                    Text("Press me!")
                }
            }
    }
    var body: some View {
        if num == 0 {
            contentWithToolbar
                .navigationSubtitle("Num is zero!")
        }
        else {
            contentWithToolbar
        }
    }
}
  1. Run the app. You should see two "Press me!" buttons even though I only have one toolbar button!

I was wondering, what is going here, and is there any way I can solve this problem?

like image 836
recaptcha Avatar asked Jan 20 '26 22:01

recaptcha


1 Answers

@Jake pointed out that the problem was caused by the 2 Text objects being stacked without a VStack.

Adding a VStack fixed the problem completely.

like image 144
recaptcha Avatar answered Jan 22 '26 13:01

recaptcha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!