4

I have a set of toolbar buttons that should be presented only if the device is iPhone (not iPad).

The following code fails with this error:

Closure containing control flow statement cannot be used with result builder 'ToolbarContentBuilder'

I do understand why it fails, but I am not be able to come up with a solution, which achieves what I need.

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            List {
                NavigationLink(
                    destination: Hello(),
                    label: {
                        Text("Hello")
                    })
            }
        }
    }
}

struct Hello: View {
    var body: some View {
        Text("Hello World")
            .toolbar() {
                if UIDevice.current.userInterfaceIdiom == .phone {
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                            // do something
                        }, label: {
                            Text("Button1")
                        })
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                            // do something
                        }, label: {
                            Text("Button2")
                        })
                    }
                }
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        // do something
                    }, label: {
                        Text("Button3")
                    })
                }
            }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I'm happy to create a separate function to achieve it. I simply can't figure out how to do it.

Satoshi Nakajima
  • 1,863
  • 18
  • 29

1 Answers1

5

Probably you wanted this

struct Hello: View {
    var body: some View {
        Text("Hello World")
            .toolbar() {
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    if UIDevice.current.userInterfaceIdiom == .phone {
                        Button(action: {
                            // do something
                        }, label: {
                            Text("Button1")
                        })
                        Button(action: {
                            // do something
                        }, label: {
                            Text("Button2")
                        })
                    }
                    Button(action: {
                        // do something
                    }, label: {
                        Text("Button3")
                    })
                }
            }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690