How to create UI programmatically in Xcode 11?

These are the steps I followed to get UI working programmatically in Xcode 11.

1) Created a new project as usual

2) I deleted the Main.Storyboard file from the project navigator on the left-hand side.

3) In General tab I removed the Main option from the Main Interface drop-down list enter image description here 4) Next, go to your Info.plist file and completely remove the Storyboard Name from the list

enter image description here

5) Now if you run the app, it should not crash and it should show you a black screen.

6) Next, go to the SceneDelegate.swift file and initialise your UIWindow object as usual. There is a catch here and is new in Xcode 11. You also set the windowScene property of the window object, or else it won't work. enter image description here

7) Once that's all done, Go to your ViewController class and set the background colour of the view to some colour and you should be all good. enter image description here

You can also use templates: Xcode 11 Programmatic UIKit templates

Hope this helped you!!!


This works for me on Xcode 10.3 Swift 5, and Xcode 11 Swift 5.1.

On your new Xcode project, on the Info.plist file, delete the launch screen and main interface file name entries, (don't leave the entry there with an empty string)

Remove the @UIApplicationMain attribute from your AppDelegate class.

Also, this link may help you, you can find info on UIApplicationMain https://docs.swift.org/swift-book/ReferenceManual/Attributes.html

See code below:

//  Created by Juan Miguel Pallares Numa on 9/16/19.
//  Copyright © 2019 Juan Miguel Pallares Numa. All rights reserved.

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var myViewController = ViewController()

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

        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = myViewController
        window?.makeKeyAndVisible()

        return true
    }
}

import UIKit

class ViewController: UIViewController {

    convenience init() {
        self.init(nibName: nil, bundle: .main)
        view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = UIColor(
            displayP3Red: 0.0, green: 0.7, blue: 0.0, alpha: 1.0)
    }
}

// call this file "main.swift"
import Foundation
import UIKit

UIApplicationMain(
    CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))

Tags:

Xcode

Swift