我如何创建一个不使用Storyboards的新Swift项目?
我如何创建一个不使用Storyboards的新Swift项目?
在XCode 6中创建一个新项目不能禁用故事板。您只能选择Swift或Objective-C以及使用或不使用Core Data。
我尝试删除storyboard,从项目中删除主storyboard,然后从didFinishLaunching手动设置窗口。
在AppDelegate中,我有这个:
class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow var testNavigationController: UINavigationController func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { testNavigationController = UINavigationController() var testViewController: UIViewController = UIViewController() self.testNavigationController.pushViewController(testViewController, animated: false) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window.rootViewController = testNavigationController self.window.backgroundColor = UIColor.whiteColor() self.window.makeKeyAndVisible() return true } }
然而,XCode给了我一个错误:
Class \'AppDelegate\' has no initializers
有人成功了吗?
admin 更改状态以发布 2023年5月24日
您必须将window
和 testNavigationController
变量标记为可选:
var window : UIWindow? var testNavigationController : UINavigationController?
Swift 类需要在实例化时初始化非可选属性:
类和结构必须在创建该类或结构的实例时将其所有存储属性设置为适当的初始值。 存储属性不能处于不确定状态。
可选类型的属性会自动初始化一个值为 nil,表示属性在初始化期间被故意设置为“尚未有值”。
在使用可选变量时,请记得使用!
对它们进行解包,例如:
self.window!.backgroundColor = UIColor.whiteColor();
不使用故事板作为rootViewController
所需的所有步骤:
1. 修改AppDelegate.swift
为:
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. 创建UIViewController
的ViewController
子类:
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue } }
3. 如果您使用Xcode模板创建项目:
- 从
Info.plist
中删除键值对"Main storyboard file base name"
。 - 删除故事板文件
Main.storyboard
。
正如您在第一个代码片段中所看到的,我不喜欢隐式解包可选项,而更喜欢使用if let
语法来解包可选的window
属性。在这里,我像if let a = a {}
这样使用它,这样可选项a
就成为if
语句中的非可选引用,与相同的名称-a
。
最后,在自己的类内引用window
属性时,self.
是不必要的。