美文网首页
SwiftUI 单独修改状态栏颜色

SwiftUI 单独修改状态栏颜色

作者: xo1988 | 来源:发表于2023-03-15 13:02 被阅读0次

有一些页面需求还是需要改变一下状态栏颜色,不过目前 swiftUI 还不支持直接通过设置的方式单独修改。目前支持的修改方式通过设置导航栏的颜色,在显示导航栏的时候可以修改状态栏的颜色,如果导航栏不显示,那么没办法,没有现成的方法修改状态栏的颜色。
设置导航栏的颜色方式如下:

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

但是不想显示标题的时候,比较难办,想了半天加了一个modifier解决了问题。
实现如下:

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

这样在需要单独修改的状态栏颜色的时候就能解决问题了,不过这种方法目前只是简单的修改全局一个颜色,如果需要修改多个颜色的话,需要把设置状态栏颜色的地方提到相应的界面中,并且在用需要的时候来回设置。

相关文章

网友评论

      本文标题:SwiftUI 单独修改状态栏颜色

      本文链接:https://www.haomeiwen.com/subject/auulrdtx.html