美文网首页Swift好文收藏
swift学习---利用protocol加载Nib

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

作者: calm1993 | 来源:发表于2018-05-18 11:04 被阅读0次

写一个加载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

    本文链接:https://www.haomeiwen.com/subject/xoawdftx.html