纯代码
自定义:
import UIKit class CustomView: UIView { var lab:UILabel! var btn:UIButton! override init(frame: CGRect) { super.init(frame: frame) //初始化 lab = UILabel() lab.textAlignment = .center lab.font = UIFont.systemFont(ofSize: 12) self.addSubview(lab) btn = UIButton() self.addSubview(btn) } override func layoutSubviews() { super.layoutSubviews() //设置 子控件 frame,也可以在这里使用自动布局 lab.frame = CGRect(x:10,y:10,width:100,height:40) btn.frame = CGRect(x:lab.frame.origin.x,y:lab.frame.maxY + 10,height:40) } //传入model对子控件进行配置,这里暂用NSObject func setUp(model:NSObject) { lab.text = "你好"//model.xx btn.setTitle("确定",for: .normal) //title:model.xx } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }使用
//纯代码 view let view = CustomView() view.frame = CGRect(x:10,y:100,width:200,height:100) view.backgroundColor = UIColor.cyan view.setUp(model: "" as NSObject) self.view.addSubview(view)
xib
自定义:
新建个view,再新建个同名的xib文件,在xib的 Identity insperctor (面板第三个按钮)里设置class为新建的view文件名
import UIKit class CustomXibView: UIView { @IBOutlet weak var nameTF: UITextField! @IBOutlet weak var sexTF: UITextField! class func instantiateFromNib() -> CustomXibView { return Bundle.main.loadNibNamed("CustomXibView",owner: nil,options: nil)?.first as! CustomXibView } //用约束在xib里设置frame override func draw(_ rect: CGRect) { super.draw(rect) //设置一些子视图的固定属性 nameTF.font = UIFont.systemFont(ofSize: 12) sexTF.font = UIFont.systemFont(ofSize: 12) } func setUp(model:NSObject) { //传入model对子控件进行配置,这里暂用NSObject nameTF.placeholder = "请输入姓名" sexTF.placeholder = "请输入性别" } }
使用
//xibView let xibView = CustomXibView.instantiateFromNib() xibView.frame = CGRect(x:10,y:view.frame.maxY + 10,height:100) self.view.addSubview(xibView)
这篇文章里有一些原理的解释: http://www.jianshu.com/p/7e47da62899c