How to add a trailing navigationbaritem conditionally to a SwiftUI View which will be presented in a NavigationView?

2.7k Views Asked by At

To add navigationBarItem to a SwiftUI View we can use code similar to this:

NavigationView {
    Text("SwiftUI")
        .navigationBarTitle("Welcome")
        .navigationBarItems(trailing: Button("Help") {
                    print("Help tapped!")
           }
        )
    }

How can this be done conditionally. Say if an array is empty show the "Help" bar button else do not show the bar button.

1

There are 1 best solutions below

3
On BEST ANSWER

You can conditionally return the button as the view or nil if the array is empty

struct ContentView: View {

    var arr = ["String"] // also test [String]()

    var body: some View {

     NavigationView {
        Text("SwiftUI")
            .navigationBarTitle("Welcome")
            .navigationBarItems(trailing: !arr.isEmpty ? Button("Help") {
                        print("Help tapped!")
                } : nil
            )
        }
    }

}