I have four buttons. I wanted to know how I would make it so that when one button is tapped by the user it highlights that button and when the user taps another button it highlights that button and unhighlights the other button. Right now when I tap the button it does nothing to highlight the button. This is the current code that I have:
extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControl.State) {
self.clipsToBounds = true // add this to maintain corner radius
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
// Do any additional setup after loading the view, typically from a nib.
button1Button.titleLabel?.adjustsFontSizeToFitWidth = true
button2Button.titleLabel?.adjustsFontSizeToFitWidth = true
button3.titleLabel?.adjustsFontSizeToFitWidth = true
button4.titleLabel?.adjustsFontSizeToFitWidth = true
button1.setBackgroundImage(UIImage(named: "button1"), for: .normal)
button1.setTitleColor(UIColor.black, for: .normal)
button2.setBackgroundImage(UIImage(named: "button2"), for: .normal)
button2.setTitleColor(UIColor.black, for: .normal)
button3.setBackgroundImage(UIImage(named: "button3"), for: .normal)
button3.setTitleColor(UIColor.black, for: .normal)
//Set background for pre-natal massage
button4.setBackgroundImage(UIImage(named: "button4"), for: .normal)
button4.setTitleColor(UIColor.black, for: .normal)
selectedMassageType = 1
buttonCatagory = .button2
highlightButtonType()
button1.titleLabel?.textAlignment = NSTextAlignment.center
button2.titleLabel?.textAlignment = NSTextAlignment.center
button3.titleLabel?.textAlignment = NSTextAlignment.center
button4.titleLabel?.textAlignment = NSTextAlignment.center
}
func highlightButtonType() {
button1.setBackgroundImage(UIImage(named: "button1"), for: .normal)
button2.setBackgroundImage(UIImage(named: "button2"), for: .normal)
button3.setBackgroundImage(UIImage(named: "button3"), for: .normal)
button4.setBackgroundImage(UIImage(named: "button4"), for: .normal)
switch selectedButtonType {
case button1.tag :
button1.setBackgroundColor(color: UIColor.customWhite, forState: .highlighted)
case button2.tag :
button2.backgroundColor = UIColor.customBlue
case button3.tag :
button3.backgroundColor = UIColor.customBlue
case button4.tag:
button4.backgroundColor = UIColor.customBlue
default: break
}
}