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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24046898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:28:00  来源:igfitidea点击:

How do I create a new Swift project without using Storyboards?

iosswiftxcode6

提问by EhTd

Creating a new project in XCode 6 doesn't allow to disable Storyboards. You can only select Swift or Objective-C and to use or not Core Data.

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

I tried deleting the storyboard and from the project removing the main storyboard and manually setting the window from didFinishLaunching

我尝试删除故事板并从项目中删除主故事板并从 didFinishLaunching 手动设置窗口

In the AppDelegate I have this:

在 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
    }
}

However, XCode gives me an error:

但是,XCode 给了我一个错误:

Class 'AppDelegate' has no initializers

“AppDelegate”类没有初始值设定项

Anyone has succeed in this?

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

采纳答案by akashivskyy

You must mark the windowand testNavigationControllervariables as optional:

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

var window : UIWindow?
var testNavigationController : UINavigationController?

Swift classes require non-optional properties to be initialized during the instantiation:

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

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

Properties of optional type are automatically initialized with a value of nil, indicating that the property is deliberately intended to have “no value yet” during initialization.

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

可选类型的属性会自动初始化为 nil 值,这表明该属性在初始化期间故意“没有值”。

When using optional variables, remember to unwrap them with !, such as:

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

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

回答by tobiasdm

All it takes for not using Storyboards for the rootViewController:

不使用 Storyboards 只需要rootViewController

1· Change AppDelegate.swiftto:

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· Create a ViewControllersubclass of UIViewController:

2· 创建一个ViewController子类UIViewController

import UIKit

class ViewController: UIViewController {

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

3· If you created the project from an Xcode template:

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

  1. Remove the key-value pair for key "Main storyboard file base name"from Info.plist.
  2. Delete the storyboard file Main.storyboard.
  1. 取出键-值对用于密钥"Main storyboard file base name"Info.plist
  2. 删除情节提要文件Main.storyboard

As you can see in the first code snippet, instead of implicitly unwrapping an optional, I rather like the if letsyntax for unwrapping the optional windowproperty. Here I'm using it like if let a = a { }so that the optional abecomes a non-optional reference inside the if-statement with the same name – a.

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

Finally self.is not necessary when referencing the windowproperty inside it own class.

在它自己的类中self.引用window属性时,finally不是必需的。

回答by Warewolf

If you want to Initialize your viewController with xib and and need to use navigation controller. Here is a piece of code.

如果你想用 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
}

回答by PREMKUMAR

Try the following code:

试试下面的代码:

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

}

回答by Hilen

You can just do it like this:

你可以这样做:

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
    }
}

回答by Yi Feng Xie

I recommend you use controller and xib

我建议你使用控制器和 xib

MyViewController.swiftand MyViewController.xib

MyViewController.swiftMyViewController.xib

(You can create through File->New->File->Cocoa Touch Class and set "also create XIB file" true, sub class of UIViewController)

(您可以通过 File->New->File->Cocoa Touch Class 创建并设置 UIViewController 的子类“也创建 XIB 文件”为真)

class MyViewController: UIViewController {
   .....    
}

and In AppDelegate.swiftfunc applicationwrite the following code

并在AppDelegate.swiftfunc application编写以下代码

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

It should be work!

应该是工作!

回答by EhTd

I have found the answer it had nothing to do with the xcode setup, removing storyboard and the reference from project is the right thing. It had to do with the swift syntax.

我发现答案与 xcode 设置无关,删除故事板和项目中的参考是正确的。它与 swift 语法有关。

The code is the following:

代码如下:

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
    }

}

回答by Tiago Martinho

Updated for Swift 3.0:

为 Swift 3.0 更新:

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

回答by Jogendra Kumar

Update: Swift 5 and iOS 13:

更新:Swift 5 和 iOS 13:

  1. Create a Single View Application.
  2. Delete Main.storyboard(right-click and delete).
  3. Delete Storyboard Namefrom the default scene configuration in the Info.plistfile: enter image description here
  4. Open SceneDelegate.swiftand change func scenefrom:
  1. 创建单一视图应用程序。
  2. 删除Main.storyboard(右键单击并删除)。
  3. 从文件中的默认场景配置中删除Storyboard NameInfo.plist在此处输入图片说明
  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 }
}

to

 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()
    }
}

回答by Dmitry Konovalov

Here is a complete swift test example for an UINavigationController

这是 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
          }
    }