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了
本文介绍了一种在SwiftUI中通过实现自定义协议来从故事板加载ViewController的方法,避免了直接使用标识符和类型转换的问题。
178

被折叠的 条评论
为什么被折叠?



