Ios 像单选按钮一样的按钮

Ios 像单选按钮一样的按钮,ios,swift,uibutton,Ios,Swift,Uibutton,我需要创建一个单选按钮一样的按钮。我试着换颜色。当我单击其中一个按钮时,所有其他按钮都变为灰色。但它们不会将颜色更改为灰色 extension UIView { func setGradientBackground(colorOne: UIColor, colorTwo: UIColor, cornerRadius: CGFloat) { let gradientLayer = CAGradientLayer() gradientLayer.frame = self.boun

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

extension 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)

   }
看起来像这样。如何修复它?

首先用单个操作分配所有按钮

然后将所有要作为单选组执行的按钮放在一个数组中

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)
        }
    }
}

setGradientBackground做什么?这很可能是这不起作用的原因,因为代码至少应该起作用。@SanderSaelmans我已经更新了。看please@SanderSaelmans我发现了我的错误。你是对的,这是因为setGradientBackground