let name = "news"
let storyboard = UIStoryboard(name: name, bundle: nil)
let identifier = "ArticleViewController"
let viewController = storyboard.instantiateViewControllerWithIdentifier(identifier) as! ArticleViewController
使用枚舉
extension UIStoryboard {
enum Storyboard: String {
case main
case news
case gallery
}
convenience init(storyboard: Storyboard, bundle: NSBundle? = nil) {
self.init(name: storyboard.rawValue, bundle: bundle)
}
class func storyboard(storyboard: Storyboard, bundle: NSBundle? = nil) -> UIStoryboard {
return UIStoryboard(name: storyboard.rawValue, bundle: bundle)
}
}
// let storyboard = UIStoryboard(storyboard: .main)
// let storyboard = UIStoryboard.storyboard(.main)
問題二:需要處理標(biāo)示符和進(jìn)行類型轉(zhuǎn)換
let storyboard = UIStoryboard.storyboard(.news)
let identifier = "ArticleViewController"
let viewController = storyboard.instantiateViewControllerWithIdentifier(identifier) as! ArticleViewController
使用協(xié)議,協(xié)議擴(kuò)展掩浙,擴(kuò)展花吟,泛型
// 協(xié)議
protocol StoryboardIdentifiable {
static var storyboardIdentifier: String { get }
}
// 協(xié)議擴(kuò)展
extension StoryboardIdentifiable where Self: UIViewController {
static var storyboardIdentifier: String {
return String(self)
}
}
// 全局一致性
extension UIViewController : StoryboardIdentifiable { }
// 泛型
extension UIStoryboard {
func instantiateViewController<T: UIViewController where T: StoryboardIdentifiable>() -> T {
let optionalViewController = self.instantiateViewControllerWithIdentifier(T.storyboardIdentifier)
guard let viewController = optionalViewController as? T else {
fatalError("Couldn’t instantiate view controller with identifier \(T.storyboardIdentifier) ")
}
return viewController
}
}
安全使用
class ArticleViewController : UIViewController{
func printHeadline() { }
}
let storyboard = UIStoryboard.storyboard(.news)
let viewController: ArticleViewController = storyboard.instantiateViewController()
viewController.printHeadline()
presentViewController(viewController, animated: true, completion: nil)