问题

我开始看看Swift编程语言,不知为何我不能正确地从特定的UIStoryboard输入一个UIViewController的初始化。

在Objective-C中,我简单地写:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardName" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"ViewControllerID"];
[self presentViewController:viewController animated:YES completion:nil];

有人能帮助我如何在斯威夫特上实现这一点吗?


当前回答

Swift 4.2更新的代码是

let storyboard = UIStoryboard(name: "StoryboardNameHere", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerNameHere")
self.present(controller, animated: true, completion: nil)

其他回答

这个答案是针对Swift 5.4和iOS 14.5 SDK进行的最新修订。


这只是新语法和稍微修改的api的问题。UIKit的底层功能并没有改变。对于绝大多数iOS SDK框架来说都是如此。

let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "myVCID")
self.present(vc, animated: true)

确保在故事板中“故事板ID”下设置myVCID。

我创建了一个库,可以用更好的语法更容易地处理这个问题:

https://github.com/Jasperav/Storyboardable

只需改变Storyboard.swift,让ViewControllers符合Storyboardable。

guard let vc = storyboard?.instantiateViewController(withIdentifier: "add") else { return }
        vc.modalPresentationStyle = .fullScreen
        present(vc, animated: true, completion: nil)

这个链接有两个实现:

迅速:

let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ViewController") as UIViewController
self.presentViewController(viewController, animated: false, completion: nil)

Objective - C

UIViewController *viewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewController"];

这个链接有在同一个故事板中初始化视图控制器的代码

/*
 Helper to Switch the View based on StoryBoard
 @param StoryBoard ID  as String
*/
func switchToViewController(identifier: String) {
    let viewController = self.storyboard?.instantiateViewControllerWithIdentifier(identifier) as! UIViewController
    self.navigationController?.setViewControllers([viewController], animated: false)

}

Swift 4.2更新的代码是

let storyboard = UIStoryboard(name: "StoryboardNameHere", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerNameHere")
self.present(controller, animated: true, completion: nil)