Programing

스토리 보드를 사용하지 않고 새 Swift 프로젝트를 생성하려면 어떻게합니까?

crosscheck 2020. 8. 12. 07:42
반응형

스토리 보드를 사용하지 않고 새 Swift 프로젝트를 생성하려면 어떻게합니까?


XCode 6에서 새 프로젝트를 생성해도 스토리 보드를 비활성화 할 수 없습니다. 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에서 오류가 발생합니다.

클래스 'AppDelegate'에는 이니셜 라이저가 없습니다.

누구든지 이것에 성공 했습니까?


windowtestNavigationController변수를 선택 사항으로 표시해야합니다 .

var window : UIWindow?
var testNavigationController : UINavigationController?

Swift 클래스는 인스턴스화 중에 초기화되는 비 선택적 속성이 필요합니다.

클래스 및 구조는 해당 클래스 또는 구조의 인스턴스가 생성 될 때까지 저장된 모든 속성을 적절한 초기 값으로 설정해야합니다. 저장된 속성은 불확실한 상태로 남을 수 없습니다.

선택적 유형의 속성은 nil 값으로 자동 초기화됩니다. 이는 초기화 중에 속성이 의도적으로 "아직 값이 없음"을 갖도록 의도되었음을 나타냅니다.

선택적 변수를 사용하는 !경우 다음과 같이로 래핑을 해제해야합니다 .

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

에 스토리 보드를 사용하지 않는 데 필요한 모든 것 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하위 클래스를 만듭니다 UIViewController.

import UIKit

class ViewController: UIViewController {

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

3 · Xcode 템플릿에서 프로젝트를 생성 한 경우 :

  1. 키의 키 - 값 쌍을 제거 "Main storyboard file base name"에서 Info.plist.
  2. 스토리 보드 파일을 삭제합니다 Main.storyboard.

첫 번째 코드 스 니펫에서 볼 수 있듯이 if let선택적 window속성 을 암시 적으로 언 래핑하는 대신 선택적 속성 을 언 래핑하는 구문을 선호합니다 . 여기서는 if let a = a { }옵션 aif동일한 이름을 가진-문 내부의 비 옵션 참조가 되도록- 처럼 사용하고 a있습니다.

마지막으로 자체 클래스 내부 self.window속성을 참조 할 때 필요하지 않습니다 .


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
}

다음 코드를 시도하십시오.

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

}

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
    }

}

다음과 같이 할 수 있습니다.

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

MyViewController.swift and MyViewController.xib

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

class MyViewController: UIViewController {
   .....    
}

and In AppDelegate.swift func application write the following code

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

It should be work!


Updated for Swift 3.0:

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

Here is a complete swift test example for an 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:

  • Create an empty application by selecting the project language as Swift.

  • Add new cocoa touch class files with the interface xib. (eg. TestViewController)

  • In the swift we have only one file interact with the xib i.e. *.swift file, there is no .h and .m files.

  • We can connect the controls of xib with swift file same as in iOS 7.

Following are some snippets for work with the controls and 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
//

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/

참고URL : https://stackoverflow.com/questions/24046898/how-do-i-create-a-new-swift-project-without-using-storyboards

반응형