问题

我开始看看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 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。

其他回答

如果你想以模态方式呈现它,你应该有如下所示的东西:

let vc = self.storyboard!.instantiateViewControllerWithIdentifier("YourViewControllerID")
self.showDetailViewController(vc as! YourViewControllerClassName, sender: self)

akashivsky的答案很好!但是,如果你从呈现的视图控制器返回时遇到一些麻烦,这个替代方法会很有用。这对我很管用!

迅速:

let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("someViewController") as! UIViewController
// Alternative way to present the new view controller
self.navigationController?.showViewController(vc, sender: nil)

Obj - c:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboardName" bundle:nil];
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"someViewController"];
[self.navigationController showViewController:vc sender:nil];

无论我怎么尝试,它都不适合我——没有错误,但我的屏幕上也没有新的视图控制器。不知道为什么,但是在超时函数中包装它最终使它工作:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.0) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "TabletViewController")
    self.present(controller, animated: true, completion: nil)
}

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

https://github.com/Jasperav/Storyboardable

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

如果你有一个Viewcontroller没有使用任何storyboard/Xib,你可以像下面这样调用这个特定的VC:

 let vcInstance : UIViewController   = yourViewController()
 self.present(vcInstance, animated: true, completion: nil)