如何从Storyboard创建init VC?

问题描述 投票:0回答:3

我必须在AppDelegate中从UIStoryboard创建init VC。

我使用.instantiateInitialViewController()但我总是没有。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let storyBoard: UIStoryboard = .init(name: "Storyboard", bundle: nil)
    if let vc = storyBoard.instantiateInitialViewController() {
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
    }

    return true
}

我的项目:

enter image description here

我没有'ViewController'文件(和类也)。为什么我总是在vc中获得'nil'?它是如何工作的?请解释。

ios swift uikit
3个回答
2
投票

storyBoard.instantiateInitialViewController返回nil的最可能原因是因为你的故事板没有初始视图控制器。您可以在故事板中选择VC并选中“是初始视图控制器”以使其成为初始视图控制器:

enter image description here

请注意,如果在项目设置中将故事板设置为“主界面”,则初始VC将自动显示。

要避免这种情况,请将此设置更改为空字符串:

enter image description here

或者,您可以在身份检查器中为VC提供标识符:

enter image description here

并使用instantiateViewController(withIdentifier)代替

storyBoard.instantiateViewController(withIdentifier: "MyVC")

1
投票

试试这个..

let navigationController = self.window?.rootViewController as! UINavigationController
    let storyboard = UIStoryboard(name: "Storyboard", bundle: nil)
    let messageVC = storyboard.instantiateViewController(withIdentifier: "YourViewControllerID")
    navigationController.pushViewController(messageVC, animated: true)

0
投票

试试这个。我总是使用这些代码在视图控制器之间导航,

  let vc = storyboard?.instantiateViewController(withIdentifier: "ViewControllerStoryBoardId") as! YourViewControllerClass
        vc.page_idenifier = "Home page"//eg:- Passing data
        navigationController?.pushViewController(vc, animated: true)
© www.soinside.com 2019 - 2024. All rights reserved.