在Swift中实例化并呈现一个viewController

问题

我开始查看Swift Programming Language,不知为何我不能从特定的UIStoryboard正确地键入UIViewController的初始化。

Objective-C中,我简单地写:

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

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

370741 次浏览

这个答案是针对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)

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

< img src = " https://i.stack.imgur.com/g0dEx.png " alt = " / >

对于使用@akashivskyy的回答实例化UIViewController并且存在异常的人:

致命错误:类使用了未实现的初始化式'init(coder:)'

快速提示:

在你要实例化的目标UIViewController处手动实现required init?(coder aDecoder: NSCoder)

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

如果你需要更多的描述,请参考我的回答在这里

// "Main" is name of .storybord file "
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
// "MiniGameView" is the ID given to the ViewController in the interfacebuilder
// MiniGameViewController is the CLASS name of the ViewController.swift file acosiated to the ViewController
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MiniGameView") as MiniGameViewController
var rootViewController = self.window!.rootViewController
rootViewController?.presentViewController(setViewController, animated: false, completion: nil)

当我把它放在AppDelegate时,这工作得很好

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];

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

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

我知道这是一个旧线程,但我认为目前的解决方案(使用硬编码的字符串标识符为给定的视图控制器)是非常容易出错。

我已经创建了一个构建时脚本(你可在此访问),它将创建一个编译器安全的方式来访问和实例化给定项目中的所有故事板中的视图控制器。

例如,在Main.storyboard中名为vc1的视图控制器将像这样实例化:

let vc: UIViewController = R.storyboard.Main.vc1^  // where the '^' character initialize the controller

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

 let vcInstance : UIViewController   = yourViewController()
self.present(vcInstance, animated: true, completion: nil)
< p >迅速3 Storyboard

.
let settingStoryboard : UIStoryboard = UIStoryboard(name: "SettingViewController", bundle: nil)
let settingVC = settingStoryboard.instantiateViewController(withIdentifier: "SettingViewController") as! SettingViewController
self.present(settingVC, animated: true, completion: {


})

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

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

斯威夫特4:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
let yourVC: YourVC = storyboard.instantiateViewController(withIdentifier: "YourVC") as! YourVC

我想建议一种更简洁的方法。当我们有多个故事板时,这将很有用

1.用你所有的故事板创建一个结构

struct Storyboard {
static let main = "Main"
static let login = "login"
static let profile = "profile"
static let home = "home"
}

2. 创建一个UIStoryboard扩展,如下所示

extension UIStoryboard {
@nonobjc class var main: UIStoryboard {
return UIStoryboard(name: Storyboard.main, bundle: nil)
}
@nonobjc class var journey: UIStoryboard {
return UIStoryboard(name: Storyboard.login, bundle: nil)
}
@nonobjc class var quiz: UIStoryboard {
return UIStoryboard(name: Storyboard.profile, bundle: nil)
}
@nonobjc class var home: UIStoryboard {
return UIStoryboard(name: Storyboard.home, bundle: nil)
}
}

将故事板标识符作为类名,并使用下面的代码进行实例化

let loginVc = UIStoryboard.login.instantiateViewController(withIdentifier: "\(LoginViewController.self)") as! LoginViewController

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

https://github.com/Jasperav/Storyboardable

只需更改Storyboard.swift并让ViewControllers符合Storyboardable

Swift 4.2更新的代码是

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

斯威夫特5

let vc = self.storyboard!.instantiateViewController(withIdentifier: "CVIdentifier")
self.present(vc, animated: true, completion: nil)
guard let vc = storyboard?.instantiateViewController(withIdentifier: "add") else { return }
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true, completion: nil)
if let destinationVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DestinationVC") as? DestinationVC{
let nav = self.navigationController
//presenting
nav?.present(destinationVC, animated: true, completion: {
                

})
//push
nav?.pushViewController(destinationVC, animated: true)
}

我使用这个助手:

struct Storyboard<T: UIViewController> {
    

static var storyboardName: String {
return String(describing: T.self)
}
    

static var viewController: T {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
        

guard let vc = storyboard.instantiateViewController(withIdentifier: Self.storyboardName) as? T else {
fatalError("Could not get controller from Storyboard: \(Self.storyboardName)")
}
        

return vc
}
}

用法(故事板ID必须匹配UIViewController类名)

let myVC = Storyboard.viewController as MyViewController