在 XCode 6 中创建新项目不允许禁用 Storyboard。您只能选择 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 给我一个错误:
“AppDelegate”类没有初始化器
有人成功过吗?
最佳答案
不为 rootViewController
使用 Storyboard 所需的一切:
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"
的键值对。 - 删除 Storyboard文件
Main.storyboard
。
正如您在第一个代码片段中看到的那样,我更喜欢使用 if let
语法来展开可选的 window
属性,而不是隐式展开可选属性。在这里,我像 if let a = a { }
这样使用它,以便可选的 a
成为 if
中的非可选引用 -具有相同名称的语句 - a
。
最后,self.
在它自己的类中引用 window
属性时不是必需的。
关于ios - 如何在不使用 Storyboard的情况下创建新的 Swift 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24046898/