I'm trying to figure out how to use the navigation bar in SwiftUI
I want to put BarButtonItem
and images inside the NavigationBar
I have been able to display the navigation bar and put titles
var body: some View {
NavigationView{
List(0...5) { note in
VStack(alignment: .leading) {
Text("title")
Text("Date")
.font(.subheadline)
.foregroundColor(.secondary)
}
}
.navigationBarTitle(Text("Notes"))
}
}
You should use .navigationBarItems()
modifier. For example you can add Button
or Image
like this:
.navigationBarItems(
leading: Button("Title") {
// Actions
},
trailing: Button(action: {
// Actions
}, label: { Image("Icon") })
)
You can have ANY View
there. (not only a Button
)
TIP
You can encapsulate each item in a struct:
struct NavigationButtonItem: View {
var body: some View {
Button("Title") {
// Actions
}
}
}
struct NavigationImageItem: View {
var body: some View {
Button(action: {
// Actions
}, label: { Image("Icon") })
}
}
And the use them like this:
.navigationBarItems(
leading: NavigationButtonItem(),
trailing: NavigationImageItem()
)