JamesG JamesG - 5 days ago 4x
iOS Question

Changing RootViewController type in Swift

Ok, I have been following along with a tutorial and I have completed that, all works fine. However the initial view that loads is a UITableViewController and I would like a UIViewController.

Here is the code for that:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

window = UIWindow(frame: UIScreen.main.bounds)

window?.rootViewController = UINavigationController(rootViewController: ViewController())

return true

I have tried editing this line:

UINavigationController(rootViewController: ViewController())


window?.rootViewController = UIViewController(rootViewController: ViewController())

But then I am given this error:

Incorrect argument label in call (have 'rootViewController:', expected 'coder:')

It then asks me to 'Fix-it' so I do, which changes the line to:

window?.rootViewController = UIViewController(coder: ViewController())

But then this now throws the error:

Cannot convert value of type 'ViewController' to expected argument type 'NSCoder'

I have also tried:

window?.rootViewController = ViewController()

but with that, the simulator goes black.

Clarify Question:

How do I get the first View that loads in my app to be of type UIViewController?


You should subclass UIViewController and make your own version to check it works, but what you're doing originally is fine

let myViewController = SomeViewController()
let navigationController = UINavigationController(rootViewController: myViewController)
window?.rootViewController = navigationController

Then in SomeViewController viewDidLoad set view.backgroundColor = .red

If you want to remove the navigation bar you can set it to hidden

navigationController.navigationBarHidden = true


let myViewController = SomeViewController()
window?.rootViewController = myViewController

Will also work... though you should be looking to keep the navigation controller in general.. it usually makes presenting view controllers a lot easier in the future...

The reason your simulator goes black is because it worked... you're showing an empty UIViewController... You must make your own UIViewController subclass and add stuff to it.

Your View Controller subclass should look like this

//  SomeViewController.swift
//  SomeProject
//  Created by Magoo on 17/10/2016.
//  Copyright © 2016 Magoo. All rights reserved.

import UIKit

class SomeViewController: UIViewController {

    override func viewDidLoad() {

        view.backgroundColor = .red

        let label = UILabel(frame:CGRect(x: 30.0, y: 30.0, width: 200.0, height: 40.0))
        label.textColor = UIColor.whiteColor()
        label.text = "Hello world"


The result should be a red screen with 'Hello world' written top left in white.