NavigationView and UIBarButtonItems in SwiftUI
Introduction
Pre-requisite for SwiftUI development :-
- Xcode 11
- MacOS Catalina 10.15.2
Getting Started
In this tutorial You’re learn the following:
- Create a Navigation View
- Create Left Bar Button
- Create Right Bar Button
- Create Both Left Bar Button and Right Bar Button
- Create Multiple Bar Button
Application Entry Point
Creating a New Project for Playing with SwiftUI. First, fire up Xcode and create a new Project. I created a project named DemoNavigationView.
Once you save the project, Xcode should load the ContentView.swift file and display a design/preview canvas.
By default, Xcode generates some SwiftUI code for ContentView.swift. However, the preview canvas doesn’t render the app preview. You have to click the Resume button in order to see the preview.
Create NavigationView
A view for presenting a stack of views representing a visible path in a navigation hierarchy.
// Default to large title styleNavigationView {
Text("Hello World")
.navigationBarTitle(Text("Navigation Title"))
}
For old style titleNavigationView {
Text("Hello World")
.navigationBarTitle(Text("Navigation Title"), displayMode: .inline)
}
Create Left Bar Button
You can add UIBarButtonItem with property .navigationBarItems(leading
.navigationBarItems(leading: Button(action: {
// Actions
}, label: { Text("Left") })
Create Right Bar Button
You can add UIBarButtonItem with property .navigationBarItems(trailing
.navigationBarItems(trailing: Button(action: {
// Actions
}, label: { Text("Right") })
Create Both Left Bar Button and Right Bar Button
You can add both UIBarButtonItem like this:
.navigationBarItems(leading: Button(action: {
// Actions
}, label: { Text("Left") }),
trailing: Button(action: {
// Actions}, label: { Text("Right") }))
Create Multiple Bar Button
You can add multiple UIBarButtonItem like this:
.navigationBarItems(leading: Button(action: {
// Actions
}, label: { Text("Left") }),
trailing: HStack {Button("About") {
// Actions
}Button("Help") {
// Actions
}})
Conclusion
I hope you enjoyed reading this. In this tutorial, we got an introduction about the Navigation View and UIBarButtonItems control of SwiftUI.
Please find the Github link.
Github:- https://github.com/imrishuj/SU-NavigationView
Thanks for reading and good luck with your next SwiftUI Tutorial!