gpt4 book ai didi

ios - UIButton 像一个单选按钮

转载 作者:行者123 更新时间:2023-11-28 13:37:24 25 4
gpt4 key购买 nike

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

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)

}

enter image description here

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

最佳答案

先给所有的按钮分配一个 Action 。

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

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

关于ios - UIButton 像一个单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56446215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com