1. Create a custom control
Import UIKit class Customview:uiview {var lab:uilabel! var btn:uibutton! /************ will need to add the child controls here to initialize *****************************/override init (frame:cgrect) {Super.init (frame: FRAME)//Initialize Lab = UILabel () lab.textalignment =. Center Lab.font = Uifont.systemfont (ofsize: Self.addsubview (Lab) BTN = UIButton () Self.addsubview (BTN)}/************ set the location of the child controls * * * * /override Func Layoutsubviews () {super.layoutsubviews ()//Set child control frame, can also be Here use automatic layout lab.frame = CGRect (X:10, Y:10, width:100, height:40) btn.frame = CGRect (x:lab.frame.origin.x, Y:lab . Frame.maxy +, width:100, height:40)}/************ incoming model sub-controls to configure, take up NSObject *****************************/ Func setUp (model:nsobject) {lab.text = "Hello"//model.xx btn.settitle ("OK", for:. Normal)//title:model.xx } Required init? (Coder Adecoder:nscoder) {FATalerror ("Init (coder:) have not been implemented")}}
2. Using a custom control
//纯代码 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)
Swift Pure Code custom control