如果使用新的应用程序生命周期,是否可以更改状态栏颜色?
我知道对于 UIKit 生命周期,有一个解决方法,您可以创建自己的 HostingController
来覆盖颜色。
但新的 SwiftUI 生命周期根本不使用 UIHostingController
。
最佳答案
这是一个可能的解决方法:
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView() // or any other loading view
.onAppear(perform: UIApplication.shared.switchHostingController)
}
}
}
class HostingController: UIHostingController<ContentView> {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension UIApplication {
func switchHostingController() {
windows.first?.rootViewController = HostingController(rootView: ContentView())
}
}
我注意到的两个缺点:
- 状态栏样式在
.onAppear
中切换 - 当您看到之前的样式时可能会出现一瞬间 ContentView
将在开始时创建两次
关于SwiftUI 生命周期应用程序 : How to change Status Bar Color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63945224/