tutorial programa primer español configurar como ios swift xcode6

ios - programa - xcode tutorial español



¿Cómo creo un nuevo proyecto Swift sin usar Storyboards? (11)

Crear un nuevo proyecto en XCode 6 no permite deshabilitar Storyboards. Solo puede seleccionar Swift u Objective-C y usar o no Core Data.

Traté de eliminar el guión gráfico y del proyecto eliminar el guión gráfico principal y configurar manualmente la ventana desde didFinishLaunching

En AppDelegate tengo esto:

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

Sin embargo, XCode me da un error:

La clase ''AppDelegate'' no tiene inicializadores

¿Alguien ha tenido éxito en esto?


¿Por qué no creas una aplicación vacía? el guión gráfico no me ha sido creado ...


Actualizado para Swift 3.0:

window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white window?.rootViewController = ViewController() window?.makeKeyAndVisible()


Aquí hay un ejemplo completo de prueba rápida para un 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://.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 } }


Debe marcar la window y testNavigationController variables testNavigationController como opcional:

var window : UIWindow? var testNavigationController : UINavigationController?

Las clases Swift requieren que las propiedades no opcionales se inicialicen durante la instanciación:

Las clases y estructuras deben establecer todas sus propiedades almacenadas en un valor inicial apropiado para el momento en que se crea una instancia de esa clase o estructura. Las propiedades almacenadas no se pueden dejar en un estado indeterminado.

Las propiedades del tipo opcional se inicializan automáticamente con un valor nulo, lo que indica que la propiedad está deliberadamente diseñada para tener "ningún valor todavía" durante la inicialización.

Cuando use variables opcionales, recuerde desenvolverlas con ! , como:

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


He encontrado la respuesta que no tiene nada que ver con la configuración xcode, eliminar el guión gráfico y la referencia del proyecto es lo correcto. Tenía que ver con la sintaxis rápida.

El código es el siguiente:

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


Podemos crear aplicaciones basadas en navegación sin guiones gráficos en Xcode 6 (iOS 8) de la siguiente manera:

  • Cree una aplicación vacía seleccionando el idioma del proyecto como Swift.

  • Agregue nuevos archivos de clase de toque de cacao con la interfaz xib. (por ejemplo, TestViewController)

  • En el instante en que solo tenemos un archivo que interactúa con el archivo xib ie * .swift, no hay archivos .hy .m.

  • Podemos conectar los controles de xib con un archivo rápido igual que en iOS 7.

Los siguientes son algunos fragmentos para trabajar con los controles y 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() } }

Cambios en el archivo 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) { } }

Encuentre ejemplos de código y otra información en http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and-work-with-controls/


Pruebe el siguiente código:

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 }


Puedes hacerlo así:

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


Si desea inicializar su viewController con xib y necesita usar el controlador de navegación. Aquí hay una pieza de código.

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 }


Te recomiendo que uses controlador y xib

MyViewController.swift y MyViewController.xib

(Puede crear a través de Archivo-> Nuevo-> Archivo-> Cocoa Touch Class y establecer "también crear archivo XIB" verdadero, subclase de UIViewController)

class MyViewController: UIViewController { ..... }

y en la func application AppDelegate.swift escriba el siguiente código

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

Debe ser trabajo!


Todo lo que se necesita para no usar Storyboards para el rootViewController :

1 · Cambie AppDelegate.swift a:

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 · Crea una subclase ViewController de UIViewController :

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue } }

3 · Si creó el proyecto a partir de una plantilla de Xcode:

  1. Elimine el par clave-valor para la clave "Main storyboard file base name" de Info.plist .
  2. Elimine el archivo del guión gráfico Main.storyboard .

Como puede ver en el primer fragmento de código, en lugar de implícitamente desenvolver un elemento opcional, prefiero la sintaxis if let para desenvolver la propiedad de window opcional. Aquí lo estoy usando como if let a = a { } para que el opcional a convierta en una referencia no opcional dentro de la declaración if con el mismo nombre - a .

Finalmente self. no es necesario al hacer referencia a la propiedad de la window dentro de su propia clase.