Search code examples
iosswiftswiftuiuibarbuttonitemios-navigationview

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


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.


Solution

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