SwiftUI 單獨(dú)修改狀態(tài)欄顏色

有一些頁面需求還是需要改變一下狀態(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è)置。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容