带有 SceneDelegate 和第一个视图的黑色背景

Black Background with SceneDelegate and First View

我尝试将视图设置为第一视图并获得黑色背景。但它应该是红色的。 这是我的 SceneDelegate:

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    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).

        guard let _ = (scene as? UIWindowScene) else { return }
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        window?.rootViewController = MainNavigationController()
        
    }

这是我的主导航控制器

import UIKit

class MainNavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
    }
}

设置root后需要添加makeKeyAndVisible() 还要将window scene赋值给window ...

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    

        guard let windowScene = (scene as? UIWindowScene) else { return }
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.windowScene = windowScene
        window?.rootViewController = MainNavigationController()
        window?.makeKeyAndVisible()
        
    }

您只需要使用 windowScene 初始值设定项而不是 frame 初始值设定项来声明 window

guard let windowScene = scene as? UIWindowScene else { return }
window = UIWindow(windowScene: windowScene)

注意:另外,如果您以编程方式加载 rootViewController,请确保故事板已禁用。