How do I create a new Swift project without using Storyboards?

后端 未结 13 880
不知归路
不知归路 2020-11-29 15:47

Creating a new project in XCode 6 doesn\'t allow to disable Storyboards. You can only select Swift or Objective-C and to use or not Core Data.

I tried deleting the s

相关标签:
13条回答
  • 2020-11-29 16:22

    All it takes for not using Storyboards for the rootViewController:

    1· Change AppDelegate.swift to:

    import UIKit
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
            window = UIWindow(frame: UIScreen.main.bounds)
            if let window = window {
                window.backgroundColor = UIColor.white
                window.rootViewController = ViewController()
                window.makeKeyAndVisible()
            }
            return true
        }
    }
    

    2· Create a ViewController subclass of UIViewController:

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = UIColor.blue
        }
    }
    

    3· If you created the project from an Xcode template:

    1. Remove the key-value pair for key "Main storyboard file base name" from Info.plist.
    2. Delete the storyboard file Main.storyboard.

    As you can see in the first code snippet, instead of implicitly unwrapping an optional, I rather like the if let syntax for unwrapping the optional window property. Here I'm using it like if let a = a { } so that the optional a becomes a non-optional reference inside the if-statement with the same name – a.

    Finally self. is not necessary when referencing the window property inside it own class.

    0 讨论(0)
提交回复
热议问题