有一些頁面需求還是需要改變一下狀態(tài)欄顏色,不過目前 swiftUI 還不支持直接通過設(shè)置的方式單獨(dú)修改。目前支持的修改方式通過設(shè)置導(dǎo)航欄的顏色,在顯示導(dǎo)航欄的時(shí)候可以修改狀態(tài)欄的顏色,如果導(dǎo)航欄不顯示,那么沒辦法,沒有現(xiàn)成的方法修改狀態(tài)欄的顏色。
設(shè)置導(dǎo)航欄的顏色方式如下:
let navibarAppearance = UINavigationBarAppearance()
navibarAppearance.configureWithOpaqueBackground()
navibarAppearance.backgroundColor = .orange
UINavigationBar.appearance().standardAppearance = navibarAppearance
UINavigationBar.appearance().compactAppearance = navibarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navibarAppearance
使用的方式如下:
VStack {
}
.navigationTitle("12")
效果如下:

1678416338009.jpg
但是不想顯示標(biāo)題的時(shí)候,比較難辦,想了半天加了一個(gè)modifier解決了問題。
實(shí)現(xiàn)如下:
struct StatusBarColorModifier: ViewModifier {
var color: UIColor
init(color: UIColor) {
self.color = color
let navibarAppearance = UINavigationBarAppearance()
navibarAppearance.configureWithTransparentBackground()
navibarAppearance.backgroundColor = color
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()
}
}
}
}
}
extension View {
func statusBarColor(_ color: Color) -> some View {
self.modifier(StatusBarColorModifier(color: UIColor(color)))
}
}
使用方式如下:
VStack {
}
.statusBarColor(.orange)
效果如下:

1678416629656.jpg
這樣在需要單獨(dú)修改的狀態(tài)欄顏色的時(shí)候就能解決問題了,不過這種方法目前只是簡單的修改全局一個(gè)顏色,如果需要修改多個(gè)顏色的話,需要把設(shè)置狀態(tài)欄顏色的地方提到相應(yīng)的界面中,并且在用需要的時(shí)候來回設(shè)置。