SwiftUI 单独修改状态栏颜色

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

let navibarAppearance = UINavigationBarAppearance()
navibarAppearance.configureWithOpaqueBackground()
navibarAppearance.backgroundColor = .orange
UINavigationBar.appearance().standardAppearance = navibarAppearance
UINavigationBar.appearance().compactAppearance = navibarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navibarAppearance

使用的方式如下:

        VStack {
            
        }
        .navigationTitle("12")

效果如下:
在这里插入图片描述
但是不想显示标题的时候,比较难办,想了半天加了一个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)

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

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xyccstudio

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值