在项目中创建swift文件,直接复制下面代码粘贴即可。
/// 有此协议并UIView遵守协议后。创建同名xib并绑定view为当前view。则可直接通过 loadFromNib 创建view。
/// 若需要添加 loadFromNib 的参数可自行添加当前view遵守NibLoadable时的 loadFromNib 方法
///如:
/**
extension NibLoadable where Self : YourCustomView {
//在协议里面不允许定义class 只能定义static
static func loadFromNib(_ nibname: String? = nil ,dat data:Array<Dictionary<String, Any>>? = nil) -> Self {
let view = UIView.loadFromNib("\(self)") as! Self
view.datas = data
return view
}
}
// 直接给自己的view添加初始化方法更好,因为class中可以直接使用supper,而不必传“/(self)"来初始化
extension YourCustomView{
class func loadFromNib(_ nibname: String? = nil ,dat data:Array<Dictionary<String, Any>>? = nil) -> Self {
let view = super.loadFromNib() as! Self
view.datas = data
return view
}
}
*/
protocol NibLoadable {
}
extension NibLoadable where Self : UIView {
//在协议里面不允许定义class 只能定义static
static func loadFromNib(_ nibname: String? = nil ) -> Self {
//Self (大写) 当前类对象 //self(小写) 当前对象
let loadName = nibname == nil ? "\(self)" : nibname!
// Bundle.main.loadNibNamed("PrepareView", owner: self, options: nil)
let view = Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self
view.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
return view
}
static func viewFromNib(_ nibname: String? = nil ) -> Self {
return loadFromNib(nibname)
}
}
extension UIView :NibLoadable{}
使用
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// let v = YourCustomView.loadFromNib() // 所有UIview 都有这个加载方法
let v = YourCustomView.loadFromNib(dat:[["1":"2"]]) // 自行为自己的view添加初始化时的入参 dat
self.view.addSubview(v)
}
网友评论