0.新建加载工具类 NibLoadable.swift
3FC21C62-DF40-4777-AB44-2D50D4BC4A5A.png
import UIKit
// 协议
protocol NibLoadable {
// 具体实现写到extension内
}
// 加载nib
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
}
}
1.新建DemoView
B672AE80-E05E-48A9-9027-64A6C2C1C391.png
2.新建xib文件(点击文件名会自动将名字补全)
C806390A-9CF0-4BE1-81DA-E0F2006F24F3.png
3.将xib与类名进行关联
A98EABAF-3A86-4239-8D7D-36CDEEFA01EC.png
4.在DemoView中遵循NibLoadable协议
import UIKit
class DemoView: UIView, NibLoadable {
// 可自定义属性
var name : String = ""
}
5.然后就可以疯狂的搞事情了
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 加载demoview
//方法一:
let demoView = DemoView.loadFromNib()
demoView.name = "why"
view.addSubview(demoView)
//方法二:
let testView = TestView.loadFromNib("")
testView.age = 10
demoView.name = "why"
}
}
网友评论