* 스토리보드의 UIViewController 가져오기

let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)

let viewController = storyboard.instantiateViewController(identifier: "ViewController")

viewController.modalPresentationStyle = .fullScreen

present(viewController, animated: true)

 

* UIStoryboard 확장해서 쉽게 불러오기

  아래 코드 추가 Storyboard가 여러개 일 경우 enum Storyboard: String 에 추가 

import UIKit

protocol StoryboardIdentifiable {
    static var storyboardIdentifier: String { get }
}

extension StoryboardIdentifiable where Self: UIViewController {
    static var storyboardIdentifier: String {
        return String(describing: self)
    }
}

extension UIStoryboard {
    
    /// The uniform place where we state all the storyboard we have in our application
    enum Storyboard: String {
        case Main = "Main"
        case Common = "Common"
        
        var filename: String {
            return rawValue.capitalized
        }
    }
    
    // MARK: - Convenience Initializers
    convenience init(storyboard: Storyboard, bundle: Bundle? = nil) {
        self.init(name: storyboard.filename, bundle: bundle)
    }
    
    // MARK: - Class Functions
    class func storyboard(_ storyboard: Storyboard, bundle: Bundle? = nil) -> UIStoryboard {
        return UIStoryboard(name: storyboard.filename, bundle: bundle)
    }
    
    // MARK: - View Controller Instantiation from Generics
    func instantiateViewController<T: UIViewController>() -> T { //where T: StoryboardIdentifiable {
        guard let viewController = self.instantiateViewController(withIdentifier: T.storyboardIdentifier) as? T else {
            fatalError("Couldn't instantiate view controller with identifier \(T.storyboardIdentifier) ")
        }
        return viewController
    }
}

extension UIViewController: StoryboardIdentifiable { }
 

 

한줄로 깔끔하게 불러올 수 있다.

let vc: MyViewController = UIStoryboard(storyboard: .Main).instantiateViewController()
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)

+ Recent posts