ios swiftui_如何:使用SwiftUI以编程方式更改iOS状态栏颜色

ios swiftui

Image for post
Source: Apple | We want to change the color of this status bar content 资料来源 :苹果| 我们要更改此状态栏内容的颜色

With UIKit, changing the color of the status bar content is as simple as:

使用UIKit,更改状态栏内容的颜色非常简单:

Unfortunately, it took quite a bit of searching (and some help from this StackOverflow question) to find a suitable solution for SwiftUI. Let’s get started!

不幸的是,它花了很多时间搜索(并从StackOverflow问题中获得了一些帮助)才能找到适用于SwiftUI的解决方案。 让我们开始吧!

First, let’s understand how SwiftUI views are attached in SceneDelegate.swift:

首先,让我们了解如何在SceneDelegate.swift中附加SwiftUI视图:

We see that the root SwiftUI view, ContentView is attached to a single UIHostingController, which is the root view controller of the key window.

我们看到根SwiftUI视图ContentView附加到单个UIHostingController ,后者是键窗口的根视图控制器。

The key to programmatically changing the status bar color is to create our own implementation of UIHostingController:

以编程方式更改状态栏颜色的关键是创建我们自己的UIHostingController实现:

Now in SceneDelegate.swift, we can simply use ContentHostingController instead of UIHostingController. But how do we retrieve the ContentHostingController in a SwiftUI view, so that we can call changeStatusBarStyle?

现在在SceneDelegate.swift ,我们可以简单地使用ContentHostingController代替UIHostingController 。 但是,我们如何在SwiftUI视图中检索ContentHostingController ,以便我们可以调用changeStatusBarStyle

In SceneDelegate, recall that we made ContentHostingController the rootViewController of our key window. We can then declare an extension on UIApplication to access these properties:

SceneDelegate ,回想一下我们将ContentHostingController rootViewController为关键窗口的rootViewController 。 然后,我们可以在UIApplication上声明扩展名以访问以下属性:

Nice! Now all we need to do in a view is something like the following:

真好! 现在,我们需要在视图中执行的操作如下所示:

And that’s it!

就是这样!

翻译自: https://medium.com/@frankjia/how-to-programmatically-change-ios-status-bar-color-with-swiftui-baf7d836aa79

ios swiftui

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值