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

时间:2014-06-04 20:23:38

标签: ios swift xcode6

在XCode 6中创建新项目不允许禁用Storyboard。您只能选择Swift或Objective-C并使用或不使用Core Data。

我尝试删除故事板,从项目中删除主故事板并从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'没有初始值设定项

有人在这方面取得了成功吗?

13 个答案:

答案 0 :(得分:87)

不使用Storyboard来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·创建ViewController的{​​{1}}子类:

UIViewController

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

  1. import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue } } 删除密钥"Main storyboard file base name"的键值对。
  2. 删除情节提要文件Info.plist
  3. 正如您在第一个代码段中看到的,我不是隐式地展开可选项,而是喜欢展开可选Main.storyboard属性的if let语法。在这里,我使用它window,以便可选的if let a = a { }成为a - 语句中具有相同名称的if的非可选引用。

    在引用其自己的类中的a属性时,最后不需要self.

答案 1 :(得分:70)

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

var window : UIWindow?
var testNavigationController : UINavigationController?

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

  

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

     

可选类型的属性会自动初始化,其值为nil,表示该属性在初始化过程中故意要“没有值”。

使用可选变量时,请记得使用!打开它们,例如:

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

答案 2 :(得分:12)

如果要使用xib初始化viewController并且需要使用导航控制器。这是一段代码。

var window: UIWindow?
var navController:UINavigationController?
var viewController:ViewController?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    window = UIWindow(frame: UIScreen.mainScreen().bounds)

    viewController = ViewController(nibName: "ViewController", bundle: nil);
    navController = UINavigationController(rootViewController: viewController!);

    window?.rootViewController = navController;
    window?.makeKeyAndVisible()

    return true
}

答案 3 :(得分:6)

请尝试以下代码:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.window!.backgroundColor = UIColor.whiteColor()

    // Create a nav/vc pair using the custom ViewController class

    let nav = UINavigationController()
    let vc = NextViewController ( nibName:"NextViewController", bundle: nil)

    // Push the vc onto the nav
    nav.pushViewController(vc, animated: false)

    // Set the window’s root view controller
    self.window!.rootViewController = nav

    // Present the window
    self.window!.makeKeyAndVisible()
    return true

}

答案 4 :(得分:2)

我找到了与xcode设置无关的答案,删除了故事板,项目中的引用是正确的。它与快速语法有关。

代码如下:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var testNavigationController: UINavigationController?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

        self.testNavigationController = UINavigationController()
        var testViewController: UIViewController? = UIViewController()
        testViewController!.view.backgroundColor = UIColor.redColor()
        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
    }

}

答案 5 :(得分:2)

你可以这样做:

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var IndexNavigationController: UINavigationController?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        var IndexViewContoller : IndexViewController? = IndexViewController()
        self.IndexNavigationController = UINavigationController(rootViewController:IndexViewContoller)
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        self.window!.rootViewController = self.IndexNavigationController
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()
        return true
    }
}

答案 6 :(得分:2)

我建议你使用controller和xib

MyViewController.swiftMyViewController.xib

(您可以通过File-> New-> File-> Cocoa Touch Class创建并设置"还可以创建XIB文件" true,UIViewController的子类)

class MyViewController: UIViewController {
   .....    
}

并在AppDelegate.swift func application中编写以下代码

....
var controller: MyViewController = MyViewController(nibName:"MyViewController",bundle:nil)
self.window!.rootViewController = controller
return true

应该有用!

答案 7 :(得分:2)

针对Swift 3.0进行了更新:

window = UIWindow()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()

答案 8 :(得分:1)

这是UINavigationController的完整快速测试示例

        import UIKit
        @UIApplicationMain
        class KSZAppDelegate: UIResponder, UIApplicationDelegate {    
          var window: UIWindow?
          var testNavigationController: UINavigationController?

          func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            // Override point for customization after application launch.        
            // Working WITHOUT Storyboard
            // see http://randexdev.com/2014/07/uicollectionview/
            // see http://stackoverflow.com/questions/24046898/how-do-i-create-a-new-swift-project-without-using-storyboards
            window = UIWindow(frame: UIScreen.mainScreen().bounds)
            if let win = window {
              win.opaque = true    
            //you could create the navigation controller in the applicationDidFinishLaunching: method of your application delegate.    
              var testViewController: UIViewController = UIViewController()
              testNavigationController = UINavigationController(rootViewController: testViewController)
              win.rootViewController = testNavigationController
              win.backgroundColor = UIColor.whiteColor()
              win.makeKeyAndVisible()
// see corresponding Obj-C in https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewControllerCatalog/Chapters/NavigationControllers.html#//apple_ref/doc/uid/TP40011313-CH2-SW1
        //      - (void)applicationDidFinishLaunching:(UIApplication *)application {
        //    UIViewController *myViewController = [[MyViewController alloc] init];
        //    navigationController = [[UINavigationController alloc]
        //                                initWithRootViewController:myViewController];
        //    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        //    window.rootViewController = navigationController;
        //    [window makeKeyAndVisible];
            //}
            }
            return true
          }
    }

答案 9 :(得分:1)

更新:Swift 5和iOS 13:

  1. 创建单视图应用程序。
  2. 删除 Main.storyboard (右键单击并删除)。
  3. Info.plist文件中的默认场景配置中删除故事板名称enter image description here
  4. 打开SceneDelegate.swift,然后从以下位置更改func scene
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let _ = (scene as? UIWindowScene) else { return }
}

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).x

    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = ViewController()
        self.window = window
        window.makeKeyAndVisible()
    }
}

答案 10 :(得分:0)

为什么不创建一个空的应用程序?故事板不是为我创造的......

答案 11 :(得分:0)

我们可以在Xcode 6(iOS 8)中创建没有故事板的基于导航的应用程序,如下所示:

  • 通过选择项目语言来创建一个空应用程序 迅速的。

  • 使用xib接口添加新的cocoa touch类文件。 (例如。 TestViewController)

  • 在swift中,我们只有一个文件与xib交互,即* .swift 文件,没有.h和.m文件。

  • 我们可以使用与iOS 7中相同的swift文件连接xib的控件。

以下是使用控件和Swift

的一些片段
//
//  TestViewController.swift
//

import UIKit

class TestViewController: UIViewController {

    @IBOutlet var testBtn : UIButton

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        // Custom initialization
    }

    @IBAction func testActionOnBtn(sender : UIButton) {
        let cancelButtonTitle = NSLocalizedString("OK", comment: "")

        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

        // Create the action.
        let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
            NSLog("The simple alert's cancel action occured.")
        }

        // Add the action.
        alertController.addAction(cancelAction)

        presentViewController(alertController, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

AppDelegate.swift文件中的更改

//
//  AppDelegate.swift
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var navigationController: UINavigationController?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()

        var testController: TestViewController? = TestViewController(nibName: "TestViewController", bundle: nil)
        self.navigationController = UINavigationController(rootViewController: testController)
        self.window!.rootViewController = self.navigationController

        return true
    }

    func applicationWillResignActive(application: UIApplication) {
}

    func applicationDidEnterBackground(application: UIApplication) {
    }

    func applicationWillEnterForeground(application: UIApplication) {
    }

    func applicationDidBecomeActive(application: UIApplication) {
    }

    func applicationWillTerminate(application: UIApplication) {
    }

}

查找代码示例和其他信息 http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and-work-with-controls/

答案 12 :(得分:0)

在iOS 13及更高版本中,当您创建没有情节提要的新项目时,请按以下步骤操作:

  1. 使用Xcode 11或更高版本创建项目
  2. 删除故事板笔尖和课程
  3. 使用xib添加新文件
  4. 需要将根视图设置为UINavigationController SceneDelegate
  5. 添加以下代码:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    // guard let _ = (scene as? UIWindowScene) else { return }
    
    if let windowScene = scene as? UIWindowScene {
        self.window = UIWindow(windowScene: windowScene)
        let mainController = HomeViewController() as HomeViewController
        let navigationController = UINavigationController(rootViewController: mainController)
        self.window!.rootViewController = navigationController
        self.window!.makeKeyAndVisible()
    }
}