Search code examples
swiftuiviewcontrollerios13xcode11

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


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.


Solution

  • 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()                 
            }
    }