SwiftUI 设置状态栏样式

iSh*_*mus 6 ios swift ios13 swiftui xcode11

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

我在几个网站上找到了这个解决方案,但无法让它工作。

HostingController.swift

import Foundation
import UIKit
import SwiftUI

class HostingController : UIHostingController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
    }
}
Run Code Online (Sandbox Code Playgroud)

这将在类声明行返回错误,Reference to generic type 'UIHostingController' requires arguments in <...>并建议修复Insert '<<#Content: View#>>'. 应用所述修复会导致错误Use of undeclared type '<#Content: View#>'

然后,您是为了改变window.rootViewControllerSceneDelegate.swift的文件。

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()
        }
Run Code Online (Sandbox Code Playgroud)

...

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

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

LuL*_*aGa 7

你的 HostingController 需要一个具体的 rootView 类型:

class HostingViewController: UIHostingController<AnyView> {

    @objc override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其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()
    }
Run Code Online (Sandbox Code Playgroud)

不幸的是,您不会在画布中看到任何区别,但请在模拟器上尝试一下。


ldi*_*ual 6

另一种扩展方式UIHostingController是保留泛型Content类型,然后就不必传递会话存储:

class HostingController<Content>: UIHostingController<Content> where Content: View {
    @objc override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的场景委托中:

window.rootViewController = HostingController(rootView: contentView)
Run Code Online (Sandbox Code Playgroud)


Ruf*_*rza 3

在 iOS 14 中,您只需要在 Info.plist 中更改/添加 2 个键:

在此输入图像描述