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


107

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'에는 이니셜 라이저가 없습니다.

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


답변:


71

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

var window : UIWindow?
var testNavigationController : UINavigationController?

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

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

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

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

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

1
끝까지 답변에서 모든 것이 완벽하게 이해됩니다. 마지막 부분을 설명해 주시겠습니까 ?? 풀다? 이것이 필요합니까?
— DanMoore 2014 년

1
선택적이 아닌 속성을 저장할 수 없습니다 AppDelegate(초기화 중에 값이 있거나 느리게 해결되지 않는 한). 선택적 속성을 저장하고 그것이 아니라고 확신 하는 경우 연산자를 nil사용하여 "선택 사항에서 래핑을 해제" !합니다.
— akashivskyy 2014 년

모범 사례는 무엇입니까, self.window! 또는 if let window = ..?
— laughingman

1
창이 존재한다고 확신하는 경우 (이 특정 경우에 확신 할 수 있음) !.
— akashivskyy

이것은 우리가 스토리 보드를 사용할 때 어떻게 든 기본적으로 설정된 backgroundColor를 의미 .white합니까?
— Honey

91

에 스토리 보드를 사용하지 않는 데 필요한 모든 것 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 { }옵션 a이 if동일한 이름을 가진-문 내부의 비 옵션 참조가 되도록 사용하고 a있습니다.

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


1
왜 if let window = window {? 나는 그것을 알아! window!매번 사용할 필요가 없습니다 .
— Bilal Akil 2014 년

@ 2unco 나는 당신이 그것을 알아 내서 기쁩니다. 이것은에 대한 내 답변의 마지막 부분에 설명되어 if let a = a {}있습니다.
— tobiasdm 2014 년

내가 할 수있는 전화 움직일 것입니다 makeKeyAndVisible()될 후 설정을 rootViewController. 그렇지 않으면 응용 프로그램 시작이 끝날 때 창에 루트 뷰 컨트롤러가있을 것으로 예상되는 방식에 대한 경고가 표시됩니다.
— Sebastien Martin

if let a = a { }이상해 보인다. 선택 사항이 아닌 참조에 동일한 변수 이름을 사용해도 괜찮습니까? Apple은 항상 Swift 문서에서 다른 이름을 사용합니다. 또한 window!매번 사용하는 것보다 왜 이것이 더 낫 습니까?
— ma11hew28 2015

1. if let a = a { }완벽합니다. 당신 if let anA = a { }이 더 편안하게 느끼면 사용할 수 있습니다 . 2. window!옵션을 명시 적으로 풀기 때문에 런타임 검사입니다. Swift가 제공하는 컴파일 시간 검사가 마음에 들기 때문에 사용하지 않는 것이 좋습니다.
— tobiasdm

13

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
}

6

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

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

}

2

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
    }

}

그러나 해결책이 다른 대답에 있다면 왜 자신의 질문에 대답합니까?
— akashivskyy

페이지가 업데이트되지 않았고 나는 게시 한 후에 만 ​​대답을 보지 못했습니다
— EhTd

2

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

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

var window : UIWindow가 있나요? 선택적 속성임을 지정 하시겠습니까?
— Sean Dunford

글쎄요, 앱 대리자에 두 번째 var를 추가하려고 시도했지만 위의 진술이 사실임을 알았습니다.
— Sean Dunford

2

컨트롤러와 xib를 사용하는 것이 좋습니다.

MyViewController.swift 과 MyViewController.xib

(File-> New-> File-> Cocoa Touch Class를 통해 생성 할 수 있으며 UIViewController의 하위 클래스 인 "XIB 파일도 생성"을 true로 설정할 수 있습니다.)

class MyViewController: UIViewController {
   .....    
}

과에서는 AppDelegate.swift func application다음과 같은 코드를 작성

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

작동해야합니다!


언급 한 것과 같은 방식으로 시도했지만 오류 : 포착되지 않은 예외 'NSInternalInconsistencyException'으로 인해 앱을 종료하는 중입니다. 이유 : '번들에 NIB를로드 할 수 없습니다 :
— shripad20

2

Swift 3.0 업데이트 :

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

2

업데이트 : Swift 5 및 iOS 13 :

  1. 단일보기 애플리케이션을 만듭니다.
  2. Main.storyboard 삭제 (오른쪽 클릭 및 삭제).
  3. 파일 의 기본 장면 구성에서 스토리 보드 이름 을 삭제 Info.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 }
}

에

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

1

다음은 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
          }
    }

0

빈 응용 프로그램을 만들지 않는 이유는 무엇입니까? 스토리 보드는 나에게 만들어지지 않았습니다 ...


0

다음과 같이 Xcode 6 (iOS 8)에서 스토리 보드없이 탐색 기반 애플리케이션을 만들 수 있습니다.

  • 프로젝트 언어를 Swift로 선택하여 빈 애플리케이션을 만듭니다.

  • xib 인터페이스를 사용하여 새 코코아 터치 클래스 파일을 추가합니다. (예 : TestViewController)

  • swift에서는 xib, 즉 * .swift 파일과 상호 작용하는 파일이 하나 뿐이며 .h 및 .m 파일은 없습니다.

  • xib의 컨트롤을 iOS 7과 동일한 빠른 파일로 연결할 수 있습니다.

다음은 컨트롤 및 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()
    }

}

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

}

http://ashishkakkad.wordpress.com/2014/06/16/create-a-application-in-xcode-6-ios-8-without-storyborard-in-swift-language-and 에서 코드 샘플 및 기타 정보 찾기 -컨트롤로 작업 /


0

iOS 13 이상에서 스토리 보드없이 새 프로젝트를 만들 때 아래 단계를 사용하세요.

  1. Xcode 11 이상을 사용하여 프로젝트 만들기

  2. 스토리 보드 펜촉 및 클래스 삭제

  3. xib로 새 파일 추가

  4. 루트 뷰를 UINavigationController SceneDelegate로 설정해야합니다.

  5. 아래 코드 추가 func scene (_ scene : UIScene, willConnectTo session : UISceneSession, options connectionOptions : UIScene.ConnectionOptions) {//이 메서드를 사용하여 UIWindow window를 선택적으로 구성하고 제공된 UIWindowScene에 연결합니다 scene. // 스토리 보드를 사용하는 경우 window속성이 자동으로 초기화되고 장면에 연결됩니다. //이 델리게이트는 연결 장면 또는 세션이 새로운 것을 의미하지 않습니다 ( application:configurationForConnectingSceneSession대신 참조 ). // 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() } }

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.