ios swiftui
![Image for post](https://img-service.csdnimg.cn/img_convert/37a677b058358b75ea806cfa48232610.png)
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!
就是这样!
ios swiftui