1.創(chuàng)建ViewModifier
//修改導(dǎo)航欄的顏色
struct StatusBarColorModifier: ViewModifier {
var color: UIColor
init(color: UIColor) {
self.color = color
let navibarAppearance = UINavigationBarAppearance()
navibarAppearance.configureWithTransparentBackground()
//修改背景的顏色
navibarAppearance.backgroundColor = color
//設(shè)置字體的顏色和大小
navibarAppearance.titleTextAttributes = [
.foregroundColor:UIColor.white,
.font:UIFont.monospacedSystemFont(ofSize: 17, weight: .black)
]
UINavigationBar.appearance().standardAppearance = navibarAppearance
UINavigationBar.appearance().compactAppearance = navibarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navibarAppearance
}
func body(content: Content) -> some View {
ZStack{
content
VStack {
GeometryReader { geometry in
Color(self.color)
.frame(height: geometry.safeAreaInsets.top)
.edgesIgnoringSafeArea(.top)
Spacer()
}
}
}
}
}
2.創(chuàng)建一個(gè)View的擴(kuò)展方便調(diào)用
extension View {
func statusBarColor(_ color: Color) -> some View {
self.modifier(StatusBarColorModifier(color: UIColor(color)))
}
}
3.調(diào)用
NavigationView {
.navigationBarHidden(false)
.navigationBarTitle(Text("導(dǎo)航欄"), displayMode: .inline)
}
.statusBarColor(.red)