我如何创建一个不使用Storyboards的新Swift项目?

25 浏览
0 Comments

我如何创建一个不使用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日
0
0 Comments

您必须将windowtestNavigationController 变量标记为可选:

var window : UIWindow?
var testNavigationController : UINavigationController?

Swift 类需要在实例化时初始化非可选属性:

类和结构必须在创建该类或结构的实例时将其所有存储属性设置为适当的初始值。 存储属性不能处于不确定状态。

可选类型的属性会自动初始化一个值为 nil,表示属性在初始化期间被故意设置为“尚未有值”。

在使用可选变量时,请记得使用对它们进行解包,例如:

self.window!.backgroundColor = UIColor.whiteColor();

0
0 Comments

不使用故事板作为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. 创建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. 删除故事板文件Main.storyboard

正如您在第一个代码片段中所看到的,我不喜欢隐式解包可选项,而更喜欢使用if let语法来解包可选的window属性。在这里,我像if let a = a {}这样使用它,这样可选项a就成为if语句中的非可选引用,与相同的名称-a

最后,在自己的类内引用window属性时,self.是不必要的。

0