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