美文网首页
使用协议方法加载XIB

使用协议方法加载XIB

作者: BYQiu | 来源:发表于2017-05-05 14:21 被阅读30次

    面向协议的方法

    创建协议 NibLoadProtocol.swift

    import Foundation
    
    protocol NibLoadProtocol {
        
    }
    
    extension NibLoadProtocol where Self : UIView {
        //在协议里面不允许定义class 只能定义static
        static func loadFromNib(_ nibname: String? = nil) -> Self {//Self (大写) 当前类对象
            //self(小写) 当前对象
            let loadName = nibname == nil ? "\(self)" : nibname!
            
            return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self
        }
    }
    

    遵守协议

    import UIKit
    
    class MyView: UIView, NibLoadProtocol {
    }
    

    使用

    // xib文件与 类名同名 的情况
    let demoView = DemoView.loadFromNib()
    
    
    // xib文件与 类名不相同 的情况
    let testV = TestView.loadFromNib("TestView0")
    
    

    相关文章

      网友评论

          本文标题:使用协议方法加载XIB

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