Comment créer un nouveau projet Swift sans utiliser Storyboards?

créer un nouveau projet dans XCode 6 ne permet pas de désactiver les Storyboards. Vous ne pouvez sélectionner Swift ou Objective-C et utiliser ou non des données de base.

j'ai essayé de supprimer le storyboard et du projet enlever le storyboard principal et le réglage manuel de la fenêtre de didFinishLaunching

Dans l'AppDelegate j'ai ceci:

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

cependant, XCode me donne une erreur:

Classe "AppDelegate" n'a pas d'initialisateurs

Quelqu'un a réussi?

100
demandé sur EhTd 2014-06-05 00:23:37

11 réponses

vous devez marquer les variables window et testNavigationController en option:

var window : UIWindow?
var testNavigationController : UINavigationController?
Les classes Swift

nécessitent des propriétés non-optionnelles à initialiser pendant l'instanciation:

les Classes et les structures doivent fixer toutes leurs propriétés stockées à une valeur initiale appropriée au moment où une instance de cette classe ou de cette structure est créée. Les propriétés stockées ne peuvent pas être laissées dans un état indéterminé.

propriétés de type optionnel sont automatiquement initialisées avec une valeur nulle, indiquant que la propriété est délibérément prévue pour avoir "aucune valeur encore" lors de l'initialisation.

lorsque vous utilisez des variables optionnelles, n'oubliez pas de les déballer avec ! , comme:

self.window!.backgroundColor = UIColor.whiteColor();
70
répondu akashivskyy 2014-06-04 20:39:08

Tout ce qu'il faut pour ne pas utiliser des story-boards pour le rootViewController :

1 * Remplacer AppDelegate.swift par:

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· Créer une ViewController sous-classe de UIViewController :

import UIKit

class ViewController: UIViewController {

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

3· Si vous avez créé le projet à partir d'un modèle Xcode:

  1. supprimer la paire de valeurs de la clé "Main storyboard file base name" de Info.plist .
  2. supprimer le fichier storyboard Main.storyboard .

comme vous pouvez le voir dans le premier extrait de code, au lieu de déballer implicitement une option, j'aime plutôt la syntaxe if let pour déballer la propriété optionnelle window . Ici, je l'utilise comme if let a = a { } de sorte que l'option a devient une référence non-optionnelle à l'intérieur de la if - déclaration avec le même nom – a .

Enfin self. n'est pas nécessaire lorsque renvoi de la propriété window à l'intérieur de sa propre catégorie.

85
répondu duemunk 2017-08-01 10:27:33

si vous voulez initialiser votre viewController avec xib et que vous devez utiliser le contrôleur de navigation. Voici un morceau de 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
}
12
répondu Warewolf 2014-11-07 10:43:29

essayez le code suivant:

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

}
6
répondu PREMKUMAR 2014-06-05 10:35:34

j'ai trouvé la réponse qu'il n'avait rien à voir avec la configuration de xcode, supprimer storyboard et la référence du projet est la bonne chose. Il avait à faire avec la swift de la syntaxe.

le code est le suivant:

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
    }

}
2
répondu EhTd 2014-06-04 20:42:47

Vous pouvez le faire comme ceci:

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
    }
}
2
répondu Hilen 2014-06-06 08:11:55

je vous recommande d'utiliser le contrôleur et xib

MyViewController.swift et MyViewController.xib

(vous pouvez créer par fichier->nouveau->fichier->Classe Cocoa Touch et définir "également créer fichier XIB" true, sous-classe de UIViewController)

class MyViewController: UIViewController {
   .....    
}

et dans AppDelegate.swift func application écrivez le code suivant

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

ça devrait marcher!

2
répondu Yi Feng Xie 2014-06-09 12:53:47

mis à jour pour Swift 3.0:

window = UIWindow()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
2
répondu Tiago Martinho 2018-06-28 07:02:34

voici un exemple de test swift complet pour un contrôleur D'Uinavigation

        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
          }
    }
1
répondu Dmitry Konovalov 2015-05-20 09:47:56

pourquoi ne pas créer une application vide? le storyboard n'est pas créé pour moi...

0
répondu allemattio 2014-06-09 18:45:10

nous pouvons créer une application basée sur la navigation sans storyboard dans Xcode 6 (iOS 8) comme suit:

  • créer une application vide en sélectionnant la langue du projet comme suit: Swift.

  • ajouter de nouveaux fichiers cocoa touch class avec l'interface xib. (eg. TestViewController)

  • dans le swift, nous n'avons qu'un seul fichier qui interagit avec le xib, c'est-à-dire *.Swift fichier, il n'est pas .h et .m fichiers.

  • nous pouvons connecter les contrôles de xib avec le fichier swift comme dans iOS 7.

voici quelques extraits pour travailler avec les commandes et 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()
    }

}

les Changements dans la AppDelegate.fichier 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) {
    }

}

trouver un exemple de code et d'autres informations sur http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and-work-with-controls /

0
répondu Ashish Kakkad 2014-06-24 05:08:31