Example 1: change navigationBar background color
ContentView.swift
struct ContentView: View {
var body: some View {
NavigationView {
ScrollView {
Text("Hello World")
.navigationBarTitle("Good", displayMode: .inline)
}
.navigationBarColor(.green) // This is how you will use it
}
}
}
NavigationBarModifiler.swift
struct NavigationBarModifier: ViewModifier {
var backgroundColor: UIColor?
init( backgroundColor: UIColor?) {
self.backgroundColor = backgroundColor
let coloredAppearance = UINavigationBarAppearance()
coloredAppearance.backgroundColor = self.backgroundColor ?? .clear
UINavigationBar.appearance().standardAppearance = coloredAppearance // still global
}
func body(content: Content) -> some View {
ZStack{
content
VStack {
GeometryReader { geometry in
Color(self.backgroundColor ?? .clear)
.frame(height: geometry.safeAreaInsets.top)
.edgesIgnoringSafeArea(.top)
Spacer()
}
}
}
}
}
extension View {
func navigationBarColor(_ backgroundColor: UIColor?) -> some View {
self.modifier(NavigationBarModifier(backgroundColor: backgroundColor))
}
}