swift 纯代码自定义控件

时间:2024-04-16 10:42:55

1、创建自定义控件

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, width:100, 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")
    }
}

2、使用自定义控件

// 纯代码 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)