Reputation: 57
I need to create button like a radio button. I try to change color. When I click on one of the buttons, all other buttons turn gray. But they do not change their color to gray.
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)
}
It looks like this. How to fix it ?
Upvotes: 1
Views: 209
Reputation: 445
Assign all the button with single action first.
Then put all the buttons you want to perform as a radio group in a single array.
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)
}
}
}
Upvotes: 2