SwiftUI 设置状态栏样式

SwiftUI setting status bar style

我一直在尝试将我的 SwiftUI 应用程序中的状态栏设置为浅色文本,因为它具有深色背景。

我在几个网站上找到了这个解决方案,但无法使用。

HostingController.swift

import Foundation
import UIKit
import SwiftUI

class HostingController : UIHostingController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
    }
}

returns class 声明行 Reference to generic type 'UIHostingController' requires arguments in <...> 上的一个错误,建议修复 Insert '<<#Content: View#>>'。应用上述修复会导致错误 Use of undeclared type '<#Content: View#>'

然后您要更改 SceneDelegate.swift 文件中的 window.rootViewController

SceneDelegate.swift

...

// Create the SwiftUI view that provides the window contents.
        let contentView = Login()

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = HostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }

...

这会在 window.rootViewController 行上引发错误 Argument passed to call that takes no arguments

有人有什么想法吗?设置状态栏颜色似乎很麻烦,我想这是一个相当普遍的要求。

您的 HostingController 需要具体类型的 rootView:

class HostingViewController: UIHostingController<AnyView> {

    @objc override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

然后在func scene(_ scene: UIScene, willConnectTo...中使用它作为rootViewController:

let contentView = ContentView()
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)

        window.rootViewController = HostingViewController(rootView: AnyView(contentView.environmentObject(SessionStore())))
        self.window = window
        window.makeKeyAndVisible()
    }

不幸的是,您在 canvas 中看不到任何差异,但请在模拟器上尝试一下。

另一种扩展 UIHostingController 的方法是保留通用 Content 类型,这样就不必通过会话存储:

class HostingController<Content>: UIHostingController<Content> where Content: View {
    @objc override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

然后在你的场景委托中:

window.rootViewController = HostingController(rootView: contentView)

我来晚了一点,但你可以更好地使用泛型:

class HostingController<ContentView: View>: UIHostingController<ContentView> {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .darkContent
    }
}

即使使用 .environmentObject() 视图修饰符,这也允许您将任何视图传递给 HostingController。

在iOS14中你只需要在Info.plist中change/add2键: