Xcode 11 & iOS13, using UIKIT can't change background colour of UIViewController

房东的猫 提交于 2019-11-26 14:57:13

问题


So I created a new project in Xcode11, set the AppDelegate to my new VC and commented the code present in xxx scene delegate to not have the UIKit part:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow()
        window?.makeKeyAndVisible()
        let controller = MainVC()
        window?.rootViewController = controller
        return true
    }

In my UIViewController I wanted to set the background colour,

import UIKit

class MainVC : UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = .red
        self.view.backgroundColor = .blue
        print("main Screen showing")
        ConfigureUI()
        setupUI()

    }

But the result is a blackScreen in Simulator. Not even taking the code from other projects would help... I've done this before in the other Xcode versions and should had work. Any ideas?

PS: The App gets in the ViewController, I can print in the console, but the screen is black.


回答1:


and commented the code present in xxx scene delegate to not have the UIKit part

You mustn't do that. It is your code that needs to go in the right place. If you make a new project in Xcode 11, this code does nothing:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    window = UIWindow()
    window?.makeKeyAndVisible()
    let controller = MainVC()
    window?.rootViewController = controller
    return true
}

The code runs, but the window property is not your app's window, so what you're doing is pointless. The window now belongs to the scene delegate. That is where you need to create the window and set its root view controller.

func scene(_ scene: UIScene, 
    willConnectTo session: UISceneSession, 
    options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {
            self.window = UIWindow(windowScene: windowScene) 
            let vc = MainVC()                                  
            self.window!.rootViewController = vc             
            self.window!.makeKeyAndVisible()                 
        }
}


来源:https://stackoverflow.com/questions/58251425/xcode-11-ios13-using-uikit-cant-change-background-colour-of-uiviewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!