简体   繁体   English

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

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

Creating a new project in XCode 6 doesn't allow to disable Storyboards.在 XCode 6 中创建新项目不允许禁用故事板。 You can only select Swift or Objective-C and to use or not Core Data.您只能选择 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?有人在这方面取得成功吗?

All it takes for not using Storyboards for the rootViewController :不为rootViewController使用 Storyboards 所需要的rootViewController

1· Change AppDelegate.swift to: 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 ViewController subclass of UIViewController : 2· 创建一个UIViewControllerViewController子类:

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 .Info.plist删除键"Main storyboard file base name"的键值对。
  2. Delete the storyboard file Main.storyboard .删除故事板文件Main.storyboard

As you can see in the first code snippet, instead of implicitly unwrapping an optional, I rather like the if let syntax for unwrapping the optional window property.正如您在第一个代码片段中看到的那样,我更喜欢用于解包可选window属性的if let语法,而不是隐式解包可选项。 Here I'm using it like if let a = a { } so that the optional a becomes a non-optional reference inside the if -statement with the same name – a .在这里,我像if let a = a { }一样使用它,以便可选的a成为if语句中的非可选引用,具有相同的名称 – a

Finally self.最后self. is not necessary when referencing the window property inside it own class.在它自己的类中引用window属性时不需要。

You must mark the window and testNavigationController variables 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();

If you want to Initialize your viewController with xib and and need to use navigation controller.如果你想用 xib 初始化你的 viewController 并且需要使用导航控制器。 Here is a piece of code.这是一段代码。

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
}

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

}

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.我发现答案与 xcode 设置无关,删除故事板和项目中的参考是正确的。 It had to do with the swift syntax.它与 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
    }

}

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

I recommend you use controller and xib我建议你使用控制器和 xib

MyViewController.swift and 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.swift func application write the following code并在AppDelegate.swift func application编写以下代码

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

It should be work!应该是工作!

Updated for Swift 3.0:为 Swift 3.0 更新:

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

Update: Swift 5 and iOS 13:更新:Swift 5 和 iOS 13:

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

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

Why don't you just create an empty application?为什么不创建一个空的应用程序? the storyboard is not created to me...故事板不是为我创建的...

We can create navigation-based application without storyboard in Xcode 6 (iOS 8) like as follows:我们可以在 Xcode 6 (iOS 8) 中创建没有故事板的基于导航的应用程序,如下所示:

  • Create an empty application by selecting the project language as Swift.通过选择项目语言为 Swift 创建一个空的应用程序。

  • Add new cocoa touch class files with the interface xib.使用界面 xib 添加新的可可触摸类文件。 (eg. TestViewController) (例如。TestViewController)

  • In the swift we have only one file interact with the xib ie *.swift file, there is no .h and .m files.在 swift 中,我们只有一个文件与 xib 交互,即 *.swift 文件,没有 .h 和 .m 文件。

  • We can connect the controls of xib with swift file same as in iOS 7.我们可以使用与 iOS 7 中相同的 swift 文件连接 xib 的控件。

Following are some snippets for work with the controls and Swift以下是使用控件和 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()
    }

}

Changes in AppDelegate.swift file 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) {
    }

}

Find code sample and other information on http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and-work-with-controls/http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and上查找代码示例和其他信息-与控件一起工作/

In iOS 13 and above when you create new project without storyboard use below steps:在 iOS 13 及更高版本中,当您创建没有情节提要的新项目时,请使用以下步骤:

  1. Create project using Xcode 11 or above使用 Xcode 11 或更高版本创建项目
  2. Delete storyboard nib and class删除故事板笔尖和类
  3. Add new new file with xib使用 xib 添加新文件
  4. Need to set root view as UINavigationController SceneDelegate需要将根视图设置为 UINavigationController SceneDelegate
  5. add below code:添加以下代码:
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()
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在没有故事板Swift的情况下推出新视图 - How to Push a New View Without Storyboards Swift 在Swift中使用情节提要时,我还应如何包含代码? - When using storyboards with Swift, how do I also include code? 如何使用Storyboard或Xib将iOS自定义键盘扩展用作Swift中的可编程自定义输入视图 - How do I use a iOS custom keyboard extension as a programmable custom input view in Swift using storyboards or xibs 如何使用swift以编程方式转换到不同故事板中的不同视图控制器? - How do I transition to a different view controllers present in different storyboards programmatically using swift? 使用Swift无需使用情节提要即可轻松进行搜索 - Unwind segue WITHOUT Storyboards using Swift 仅使用情节提要,如何创建可以使用UIScrollView左右滚动的UITableViewCell? - With Storyboards only, how do I create a UITableViewCell that can scroll left and right using UIScrollView? XCode 6情节提要-如何为每个场景创建标题? - XCode 6 storyboards - how do I create a header for every scene? 我如何使用Swift创建新数组? - How to i create new arrays using swift? Firebase Swift:如何使用“用户”集合下的 UID 创建新集合? - Firebase Swift: How do I create a new collection using the UID under my “users” collection? 当在 Swift 5 中点击 Tableview Row 时,如何使用 Xib(不是 StoryBoards)在 SideMenu Controller 中设置 UINavigationController 以推送新的 ViewController - How to set UINavigationController in SideMenu Controller using Xib (Not StoryBoards) to push new ViewController when Tableview Row Tapped in Swift 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM