【发布时间】:2021-12-30 00:55:52
【问题描述】:
我正在尝试在最新的 SwiftUI 生命周期中设置状态栏样式。这是我执行此操作的逻辑的代码,改编自 here。
private class HostingController<Content: View>: UIHostingController<Content> {
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIApplication.statusBarStyleHierarchy.last ?? UIApplication.defaultStatusBarStyle
}
}
/// By wrapping views in a StatusBarControllerView, they will become the app's main / primary view.
/// This will enable setting the statusBarStyle.
struct StatusBarControllerView<Content: View>: View {
var content: Content
init(@ViewBuilder content: () -> (Content)) {
self.content = content()
}
var body:some View {
EmptyView()
.onAppear {
UIApplication.shared.setHostingController(rootView: AnyView(content))
}
}
}
extension View {
/// Sets the status bar style color for this view.
func statusBar(style: UIStatusBarStyle) -> some View {
UIApplication.statusBarStyleHierarchy.append(style)
return self
// Once this view appears, set the style to the new style.
.onAppear {
UIApplication.hostingController?.setNeedsStatusBarAppearanceUpdate()
}
// Once it disappears, set it to the previous style.
.onDisappear {
UIApplication.statusBarStyleHierarchy.removeLast()
UIApplication.hostingController?.setNeedsStatusBarAppearanceUpdate()
}
}
}
private extension UIApplication {
static var hostingController: HostingController<AnyView>?
static var statusBarStyleHierarchy: [UIStatusBarStyle] = []
static let defaultStatusBarStyle: UIStatusBarStyle = .lightContent
/// Sets the App to start at rootView
func setHostingController(rootView: AnyView) {
let hostingController = HostingController(rootView: AnyView(rootView))
windows.first?.rootViewController = hostingController
UIApplication.hostingController = hostingController
}
}
然后我将 StatusBarControllerView 放在我的根 App 中,如下所示:
@main
struct App: SwiftUI.App {
var body: some Scene {
WindowGroup {
StatusBarControllerView {
Text("Content goes here")
}
}
}
}
虽然它在视觉上运行良好,但我现在在控制台中收到以下错误:
Unbalanced calls to begin/end appearance transitions for <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x13ee0d9d0>.
有谁知道如何修改提供的代码以避免出现此错误消息?在private extension UIApplication中设置根视图控制器时出现问题:
windows.first?.rootViewController = hostingController
2021 年 1 月 3 日澄清
我尝试以这种方式更改状态栏颜色而不是通过编辑 plist 的原因是因为我希望能够在我的应用程序的任何视图中动态更改状态栏颜色,而不是在应用程序范围内,如下图:
struct MyView: View {
var body: some View {
MySubview()
.statusBar(style: .darkContent)
}
}
【问题讨论】:
-
欢迎来到 SO - 请使用 tour 并阅读 How to Ask 以改进、编辑和格式化您的问题。如果没有Minimal Reproducible Example,就无法帮助您解决问题。
-
我现在已经编辑了我的问题以回应 3 个不喜欢。具体来说,我将我的代码添加到问题本身(而不是链接它),并通过将其变成问题来改进标题。如果您对我的问题仍有不满意的方面,请在此处发表评论,以便我做出您想要的改进。