Customize NavigationBar in SwiftUI
In this story, I’m going to talk about how to customize NavigationBar in SwiftUI.
The NavigationBar in SwiftUI provides an easy way to navigate between different views in your app. It also comes with a built-in Toolbar that you can use to add buttons, icons, and other controls to the NavigationBar. However, the default style of the NavigationBar may not always match the design requirements of your app. Fortunately, SwiftUI provides several ways to customize the NavigationBar, including the Toolbar.
Let’s start by creating a simple SwiftUI project with a NavigationView:
struct CustomNavigation: View {
var body: some View {
NavigationView {
Text("Hello, World!")
.navigationTitle("Custom Navigation")
}
}
}
The navigationTitle
modifier sets the title of the NavigationBar to "Custom Navigation". Now, let's customize the NavigationBar by adding a Toolbar with some controls. We can do this by using the toolbar
modifier and passing in a ToolbarItemGroup:
struct CustomNavigation: View {
var body: some View {
NavigationView {
Text("Hello, World!")
.navigationTitle("Custom Navigation")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
Button(action: {
// handle tap
}) {
Image(systemName: "plus")
}
Button(action: {
// handle tap
}) {
Image(systemName: "ellipsis")
}
}
}
}
}
}
In this example, we add a ToolbarItemGroup to the NavigationBar’s trailing edge by using the .navigationBarTrailing
placement. Inside the ToolbarItemGroup, we add two Button controls, each with its own action and icon.
You can also customize the style of the NavigationBar itself by using the .navigationBarColor
modifier. This modifier lets you set the background and text colors of the NavigationBar. For example:
struct CustomNavigation: View {
init() {
UINavigationBar.appearance().backgroundColor = UIColor(red: 0.2, green: 0.5, blue: 0.8, alpha: 1)
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.white]
}
var body: some View {
NavigationView {
Text("Hello, World!")
.navigationTitle("Custom Navigation")
}
.navigationBarColor(UIColor(red: 0.2, green: 0.5, blue: 0.8, alpha: 1))
}
}
In this example, we set the background color of the NavigationBar using the .navigationBarColor
modifier. We also customize the text color of the large title by setting the largeTitleTextAttributes
of the NavigationBar using the appearance()
method.
Overall, customizing the NavigationBar in SwiftUI is a simple and intuitive process. You can use the built-in Toolbar to add controls to the NavigationBar, and you can use the .navigationBarColor
modifier to change the style of the NavigationBar itself. With these tools at your disposal, you can easily create NavigationBars that match the design requirements of your app.