首页 > 解决方案 > UIButton 就像一个单选按钮

问题描述

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

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)

   }

在此处输入图像描述

它看起来像这样。如何解决? 在此处输入图像描述

标签: iosswiftuibutton

解决方案


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

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

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

推荐阅读