Search code examples
iosswiftuibuttoninterface-builderibaction

How do I change the color of my custom UIButton's that is registered with IBAction?


I have created a custom UIButton called RegistrationButton. I am currently trying to allow a user to select between three buttons. On select of a button the background color and text will change. Here is how the IBAction looks:

  @IBAction func didTapBUtton(_ sender: UIButton) {


  switch sender {
    case studentButton:
        studentButton.selected()
        professionalButton.notSelected()
        entrepreneurhsip.notSelected()
        break
    case professionalButton:
        studentButton.notSelected()
        professionalButton.selected()
        entrepreneurhsip.notSelected()
        break
    case entrepreneurhsipButton:
        studentButton.notSelected()
        professionalButton.notSelected()
        entrepreneurhsip.selected()
        break
    default:
        break
    }
}

Here is how my custom UIButton class:

import UIKit

class RegistrationButton: UIButton {


override func awakeFromNib() {
    super.awakeFromNib()
    addBorder()

}

required init(coder:NSCoder) {
    super.init(coder:coder)!
}

func addBorder(){
    self.layer.borderColor = UIColor.white.cgColor
    self.layer.borderWidth = 1
}

func selected(){
     self.backgroundColor = .white

    self.setTitleColor(UIColor(red:67,green:204,blue:144,alpha:1), for: .normal)
}
func notSelected(){

    self.backgroundColor = UIColor(red:67,green:204,blue:144,alpha:1)


    self.setTitleColor(UIColor.white, for: .normal)
}

}

However, when I select on one button the background of all is changed to white. enter image description here


Solution

  • The rgb values have to be floating points between 0 and 1. You just need to divide all of your parameters by 255 to make it work.

    So for example

    self.backgroundColor = UIColor(red:67,green:204,blue:144,alpha:1)
    

    should be

    self.backgroundColor = UIColor(red: 67.0/255, green: 204.0/255, blue:144.0/255, alpha:1)
    

    (the same obviously applies when you apply the title color)

    Sidenote: A switch in Swift does not fallthrough by default, so you can omit the breaks. If you explicitly need this behaviour, then there is a fallthrough keyword for that.