swift学习---利用protocol加载Nib

写一个加载NibLoadable的协议,然后拓展到UIViewController和UIView中

protocol NibLoadable {}

extension NibLoadable where Self : UIView {
    static func loadFromNib(_ name : String? = nil) -> Self {
        let loadName = name == nil ? "\(self)" : name!
        return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self
    }
}
extension NibLoadable where Self : UIViewController {
    static func loadFromStoryboard(_ name: String? = nil, withIdentifier: String? = nil) -> Self {
        
        let loadName = name == nil ? "\(self)" : name!
        guard let sbId = identifier else {
            return UIStoryboard(name: loadName, bundle: nil).instantiateInitialViewController() as! Self
        }
        
        return UIStoryboard(name: loadName, bundle: nil).instantiateViewController(withIdentifier: sbId) as! Self
    }
}
extension UIViewController: NibLoadable {}
extension UIView: NibLoadable {}

然后:

        let writeVC = WriteViewController.loadFromStoryboard()
        
        let medalView = MedalView.loadFromNib()

你可能感兴趣的:(swift学习---利用protocol加载Nib)