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)