- 创建一个 Swift File 文件实现
NibLoadable
协议
import UIKit
protocol NibLoadable {
}
extension NibLoadable where Self : UIView {
static func loadFromNib(_ nibname : String? = nil) -> Self {
let loadName = nibname == nil ? "\(self)" : nibname!
return Bundle.main.loadNibNamed(loadName, owner: nil, options: nil)?.first as! Self
}
}
- 需要使用该协议的view需遵守该协议
import UIKit
class DemoView: UIView, NibLoadable {
var name : String = ""
}
- 从
nib
初始化方法
let demoView = DemoView.loadFromNib()
或
let demoView = DemoView.loadFromNib("DemoView")
网友评论