1.创建ViewModifier
//修改导航栏的颜色
struct StatusBarColorModifier: ViewModifier {
var color: UIColor
init(color: UIColor) {
self.color = color
let navibarAppearance = UINavigationBarAppearance()
navibarAppearance.configureWithTransparentBackground()
//修改背景的颜色
navibarAppearance.backgroundColor = color
//设置字体的颜色和大小
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.创建一个View的扩展方便调用
extension View {
func statusBarColor(_ color: Color) -> some View {
self.modifier(StatusBarColorModifier(color: UIColor(color)))
}
}
3.调用
NavigationView {
.navigationBarHidden(false)
.navigationBarTitle(Text("导航栏"), displayMode: .inline)
}
.statusBarColor(.red)