Swift View的简单封装

在项目中,我们常常需要自定义view,那么在Swift中,是怎么自定义的呢?
以下是在自定义view中的写法

import UIKit

class YHView: UIView {
    
    public let bottomLine : UIView = {
        let line = UIView()
        line.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 100)
        line.backgroundColor = UIColor.orange
        line.isHidden = false
        
        let icon = UIImageView()
        icon.image = UIImage.init(named: "TextField_password_select")
        icon.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
        line.addSubview(icon)
        
        
        return line
    }()
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        self.addSubview(bottomLine)
    }
}

那在VC中,使用方法如下:

import UIKit

class ViewController: UIViewController {
 
    let yhView :YHView = {
        
        let yhView = YHView(frame: CGRect(x: 0, y: 300, width: UIScreen.main.bounds.size.width, height: 20))
        yhView.bottomLine.backgroundColor = UIColor.blue
        
        return yhView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(yhView)

    }

}

推荐阅读更多精彩内容