ios - 如何在不使用 Storyboard的情况下创建新的 Swift 项目?

标签 ios swift xcode6

在 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·创建UIViewControllerViewController子类:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.blue
    }
}

3· 如果您从 Xcode 模板创建项目:

  1. Info.plist 中删除键 "Main storyboard file base name" 的键值对。
  2. 删除 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/

相关文章:

ios - 将数据发布到数据库字段,但字段仍为空白?

iOS Swift - 如何更改表格 View 的背景颜色?

ios - 设置 Controller 时 NSFetchedResultsController 崩溃

swift - 从 SpriteKit 场景切换到 Swift 中的 UIView

ios - 快速代码崩溃,记录 : dyld: Library not loaded: @rpath/libswiftCore. dylib

enums - 使用 Xcode 6.1 的 Swift 枚举 .toRaw 和 .fromRaw

terminal - Xcode 6 - 如何从终端在 IOS Simulator Mobile Safari 中打开 Url?

ios - 更新核心数据性能

ios - 在 Xcode 中,如何以编程方式从 .icns 文件中提取 .png 图像?

string - 有没有办法在 swift 中从 utf16 数组创建字符串?