SwiftUI

SwiftUI 修改Status Bar颜色

有时候,我们需要修改App的状态栏颜色,在SwiftUI中,UIHostingController所有view的根,我们可以通过修改UIHostingController来改变颜色。

class MyHostingController<ContentView>: UIHostingController<ContentView> where ContentView : View {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}
import UIKit
import SwiftUI
import VitalSign

class SceneDelegate: UIResponder, UIWindowSceneDelegate, VSSensorManagerDelegate, VSMonitorDelegate {

    var window: UIWindow?
    var sensorManager: VSSensorManager!
    var monitor: VSMonitor!


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

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

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