封装StoryBoard初始化

定义className:

extension NSObject {
    
    class var className: String {
        return String(describing: self)
    }
    
    var className: String {
        return type(of: self).className
    }
}

定义初始化方法:

public protocol IBInitializable {}

// MARK: - UIView

extension UIView: IBInitializable { }

public extension IBInitializable where Self: UIView {
    
    static func instantiate(withOwner owner: Any? = nil) -> Self {
        let nib = UINib(nibName: self.className, bundle: Bundle(for: self))
        return nib.instantiate(withOwner: owner, options: nil)[0] as! Self
    }
    
}

// MARK: - UIViewController

extension UIViewController: IBInitializable { }

public extension IBInitializable where Self: UIViewController {
    
    static func instantiate() -> Self {
        return instantiate(withStoryboard: className, withIdentifier: className)
    }
    
    static func instantiate(withStoryboard storyboard: String, withIdentifier identifier: String) -> Self {
        let storyboard = UIStoryboard(name: storyboard, bundle: nil)
        guard let viewController = storyboard.instantiateViewController(withIdentifier: identifier) as? Self else {
            fatalError("\(self.className) 生成失败")
        }
        
        return viewController
    }
    
    static func instantiateWithNavigationController() -> (navigationController: UINavigationController, viewController: Self) {
        let viewController = instantiate()
        let navigationController = UINavigationController(rootViewController: viewController)
        
        return (navigationController, viewController)
    }
}

你可能感兴趣的:(封装StoryBoard初始化)