swift 购物车添加按钮

2020-03-24  本文已影响0人  艾欧尼亚
截屏2020-03-24下午2.59.07.png
import UIKit

class GoodsAddNumView: UIView {

    private lazy var reductionBtn: UIButton = {
        let button = UIButton.init(type: .custom)
        button.backgroundColor = UIColor(hexString: "#f6f6f6")
        button.setImage(UIImage(name: ""), for: .normal)
        button.setTitle("-", for: .normal)
        button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
        return button
    }()
    
    private lazy var addButton: UIButton = {
        let button = UIButton.init(type: .custom)
        button.backgroundColor = UIColor(hexString: "#f6f6f6")
        button.setImage(UIImage(name: ""), for: .normal)
        button.setTitle("+", for: .normal)
        button.setTitleColor(UIColor(hexString: "#666666"), for: .normal)
        return button
    }()
    
    private lazy var numLab: UILabel = {
        let label = UILabel.init()
        label.textColor = UIColor(hexString: "#1a1a1a")
        label.font = UIFont.systemFont(ofSize: 12)
        label.backgroundColor = UIColor(hexString: "#f6f6f6")
        label.textAlignment = .center
        return label
    }()
    
    private var num : Int = 0
    
    var getNumBlock : ((_ num: Int,_ add: Int) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
        addButton.addTarget(self, action: #selector(addButtonClick), for: .touchUpInside)
        reductionBtn.addTarget(self, action: #selector(reductionBtnClick), for: .touchUpInside)
        numLab.text = "\(num)"
    }
    
    func setUI() {
        addSubview(self.addButton)
        addSubview(self.reductionBtn)
        addSubview(numLab)
        
        reductionBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.bottom.equalToSuperview()
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
        numLab.snp.makeConstraints { (make) in
            make.left.equalTo(reductionBtn.snp.right).offset(5)
            make.right.equalTo(addButton.snp.left).offset(-5)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
        addButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.top.bottom.equalToSuperview()
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
    }
    
    @objc func addButtonClick() {
        if num >= 0 {
            num += 1
        }
        self.numLab.text = "\(num)"
        self.getNumBlock?(num, 1)
    }
    
    @objc func reductionBtnClick() {
        guard num > 0 else {
            return
        }
        num -= 1
        self.numLab.text = "\(num)"
        self.getNumBlock?(num, -1)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

上一篇下一篇

猜你喜欢

热点阅读