2

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Rohan Bhale
  • 1,323
  • 1
  • 11
  • 29

1 Answers1

10

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

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Hmm... it works, but it is strange, 'cause by interface contract `nil` should not be accepted. Could not be it side-effect of...? – Asperi Dec 09 '19 at 10:50
  • @Asperi exactly the reason I asked this question. Seemed to me that the view to return should be non optional. Is there a possible explaination how this answer works? – Rohan Bhale Dec 09 '19 at 11:10
  • 1
    IMO more correctly to use `EmptyView()` instead of `nil`. – Asperi Dec 09 '19 at 11:12