在 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
中删除键“主 Storyboard文件基本名称”
的键值对。 - 删除 Storyboard文件
Main.storyboard
。
正如您在第一个代码片段中所看到的,我更喜欢使用 if let
语法来解包可选的 window
属性,而不是隐式解包可选属性。在这里,我像 if let a = a { }
一样使用它,以便可选的 a
成为 if
内的非可选引用 -具有相同名称的语句 - a
。
最后,在引用自己的类中的 window
属性时,不需要 self.
。
关于ios - 如何在不使用 Storyboard 的情况下创建新的 Swift 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36877337/