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 中删除键 “主 Storyboard文件基本名称” 的键值对。
  2. 删除 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/

相关文章:

ios - 如何仅从该 UIView 的特定区域拖动我的 UIView?

ios - 如何在 swift 中使用带有结构的嵌套 json

swift - 在我的应用程序中集成 iAd 前置视频集成?

ios - Xcode6 中 swift 无法解析的标识符 "PFFacebookUtils"

ios - 如何在不重新加载整个 TableView 的情况下更新自定义节标题?

ios - 在 uitableviewcell 中切换复选框图像

ios - 如何使用 Swift 使用 FileManager 将文件永久保存到 iCloud?

ios - 在 iPhone 6 Plus 上关闭 UISplitViewController 弹出窗口时 UIWebView 拉伸(stretch)

ios - NSURLSession : Get Json from NSURLResponse

ios - 未为约束准备 View 层次结构