• Swift 使用Xib自定义View


    参考自:http://www.voidcn.com/article/p-rummufan-cn.html

    Xib

    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 = "请输入性别"
        }
    
    }
    

    使用

    let xibView = CustomXibView.instantiateFromNib()
            xibView.frame = CGRect(x:10, y:view.frame.maxY + 10, 200, height:100)
            self.view.addSubview(xibView)
    

    纯代码

    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, 100, height:40)
    
            btn.frame = CGRect(x:lab.frame.origin.x, y:lab.frame.maxY + 10, 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")
        }
    
    }
    

    使用

    //纯代码 view
            let view = CustomView()
            view.frame = CGRect(x:10, y:100, 200, height:100)
            view.backgroundColor = UIColor.cyan
            view.setUp(model: "" as NSObject)
            self.view.addSubview(view)
    
    此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
  • 相关阅读:
    一般查找 (顺序查找)
    sscanf
    uva-11044-水题
    uva-10785-模拟水题
    uva-10596-欧拉回路
    uva-10879-因数分解
    uva-10562-二叉树
    扯皮的cplex-感觉时间不对
    cplex-Java-样例代码解析
    cplexJava源码---计算结果
  • 原文地址:https://www.cnblogs.com/liuw-flexi/p/12869489.html
Copyright © 2020-2023  润新知