storyboard加载viewcontroller protocol实现

来源:互联网 发布:听歌识曲的软件 编辑:程序博客网 时间:2024/04/27 13:33
@objc(ABLoadFromStoryboardProtocol)
protocol ABLoadFromStoryboardProtocol: class {
    
    static func loadFromStoryboard() -> UIViewController
}

extension UIViewController {
    
    static func loadFromStoryboard<T: ABLoadFromStoryboardProtocol>(_: T.Type) -> T {
        
        if let vc = T.loadFromStoryboard() as? T {
            return vc
        }
        
        fatalError("Could not instantiateViewController from storyboard")
    }

}

需要加载的viewcontroller需要实现ABLoadFromStoryboardProtocol协议


extension CustomViewController: ABLoadFromStoryboardProtocol {

    static func loadFromStoryboard() -> UIViewController {

         return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "custom_view_story_identifier")

    }

}


加载调用方法

let customVC = UIViewController.loadFromStoryboard(CustomViewController.self)

现在这种方式就不需要每次找到identifier才能加载和强制转换为指定的viewcontroller了

0 0