問題

我一直在嘗試將我的SwiftUI應用程式中的statusbar設定為光文字,因為它有一個黑暗的背景.

我在幾個網站上找到了這個解決方案,但無法讓它工作.

HostingController.swift

 import Foundation
import UIKit
import SwiftUI

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

這會返回類宣告行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.rootViewControllerArgument 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()
    }
 

不幸的是,您在畫布上看不到任何區別,但在模擬器上嘗試它.

  相同標籤的其他問題

iosswiftswiftuiios13xcode11