如何使UIButton背景图像具有渐变(Swift)

时间:2018-07-27 03:28:15

标签: swift uibutton gradient

enter image description here

每个人都请帮助我如何制作这样的UIButton,我之前已经搜索过解决方案,但没有任何人。谢谢!

1 个答案:

答案 0 :(得分:2)

声明新的按钮子类:

class GradientButton : UIButton {

    var leftColor = UIColor.red
    var rightColor = UIColor.green
    var customImage : UIImage? {
        didSet {
            updateImageView()
        }
    }
    let gradientLayer = CAGradientLayer()
    let customImageView = UIImageView()

    override var frame: CGRect {
        didSet {
            gradientLayer.frame = bounds
            layer.layoutIfNeeded()
        }
    }

    convenience init(leftColor: UIColor, rightColor: UIColor, image: UIImage) {
        self.init()

        self.leftColor = leftColor
        self.rightColor = rightColor
        customImage = image
        updateImageView()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        defaultInitializer()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        defaultInitializer()
    }

    func defaultInitializer() {

        gradientLayer.frame = bounds
        gradientLayer.colors = [leftColor.cgColor, rightColor.cgColor]
        gradientLayer.startPoint = CGPoint.init(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint.init(x: 1, y: 0.5)
        layer.insertSublayer(gradientLayer, at: 0)
        layer.layoutIfNeeded()

        addSubview(customImageView)
        customImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }

    func updateImageView() {
        customImageView.image = customImage
        customImageView.alpha = 0.2
        layoutSubviews()
    }
}

初始化类似:

    let rect = CGRect(x: 20, y: 20, width: 200, height: 100)
    let button = GradientButton(leftColor: UIColor.red, rightColor: UIColor.cyan, image: UIImage(named: "1")!)
    button.frame = rect
    self.view.addSubview(button)

甚至还有情节提要。

其他设置,如文本颜色,字体等,可以在UIButton声明中找到。 编码愉快!