UIButton像单选按钮一样

时间:2019-06-04 14:44:30

标签: swift uibutton

我需要像单选按钮一样创建按钮。我尝试改变颜色。当我单击其中一个按钮时,所有其他按钮变为灰色。但是它们不会将颜色更改为灰色。

extansion UIView 

func setGradientBackground(colorOne: UIColor, colorTwo: UIColor, cornerRadius: CGFloat) {

    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.bounds
    gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
    gradientLayer.locations = [0.0, 1.0]
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
    gradientLayer.cornerRadius = cornerRadius

    layer.insertSublayer(gradientLayer, at: 10)
}

@IBAction func oneButtonAction(_ sender: Any) {
    oneButton.setGradientBackground(colorOne: UIColor(red: 0, green: 0.52, blue: 1, alpha: 1), colorTwo: UIColor(red: 0, green: 0.39, blue: 0.81, alpha: 1), cornerRadius: oneButton.frame.height/2)
    twoButton.backgroundColor = UIColor(red: 0.94, green: 0.96, blue: 0.98, alpha: 1)
}

@IBAction func twoButtonAction(_ sender: Any) {
    oneButton.backgroundColor = UIColor(red: 0.94, green: 0.96, blue: 0.98, alpha: 1)
    twoButton.setGradientBackground(colorOne: UIColor(red: 0, green: 0.52, blue: 1, alpha: 1), colorTwo: UIColor(red: 0, green: 0.39, blue: 0.81, alpha: 1), cornerRadius: oneButton.frame.height/2)

}

enter image description here

看起来像这样。如何解决? enter image description here

1 个答案:

答案 0 :(得分:1)

首先通过一次操作分配所有按钮。

然后将要作为无线电组执行的所有按钮都放在一个阵列中。

let buttonGroup: [UIButton] = [button1, button2, button3]

@IBAction func buttonAction(_ sender: UIButton) {
    buttonGroup.forEach { button in
        if button == sender {
            button.setGradientBackground(colorOne: UIColor(red: 0, green: 0.52, blue: 1, alpha: 1), colorTwo: UIColor(red: 0, green: 0.39, blue: 0.81, alpha: 1), cornerRadius: oneButton.frame.height/2)
        } else {
            button.backgroundColor = UIColor(red: 0.94, green: 0.96, blue: 0.98, alpha: 1)
        }
    }
}