问题

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

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

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

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


当前回答

我使用这个助手:

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

其他回答

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

对于那些使用@akashivsky的答案来实例化UIViewController的人来说,有一个异常:

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

快速提示:

手动实现所需的初始化?(coder aDecoder: NSCoder)在你的目标UIViewController,你试图实例化

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时,这工作得很好

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