SwiftUI: How to show some toolbar buttons only for iPhone

785 views Asked by At

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.

1

There are 1 answers

0
Asperi On

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")
                    })
                }
            }
    }
}