Swift: Change a button color once pressed

40,827

Solution 1

This is pretty simple.

You'll start off by first actually setting up the button's background colour in the ViewDidLoad() method. Before this, you should have already set up an IBOutlet for the button. In my example, I'm just going to name the outlet a generic "button".

Your IBOutlet would be:

@IBOutlet weak var button:UIButton!

Don't forget to hook up the outlet to the button as well!

Next, set the button's background image to gray in ViewDidLoad, like so:

override func viewDidLoad() {
    super.viewDidLoad()

    button.backgroundColor = UIColor.grayColor()
}

This should give your button a generic gray background. If you want more control over the actual colour, you can replace button.backgroundColor = UIColor.grayColor() with button.backgroundColor = UIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat), replacing "CGFloat" with the values you choose.

Next, the actual code to change the button colour:

Make an IBAction and wire it up to the button. Mine is called:

@IBAction func buttonTapped(sender: AnyObject) {}

Your condition is that if the button is grey, it should become blue on tap and if it is blue, then it should become gray on tap.

So, within the IBAction that we just defined, you'll add an If Statement, like so:

@IBAction func buttonTapped(sender: AnyObject) {
    if button.backgroundColor == UIColor.grayColor() {
        button.backgroundColor = UIColor.blueColor()
    }
    else if button.backgroundColor == UIColor.blueColor() {
        button.backgroundColor = UIColor.grayColor()
    }
}

What this if statement does is that if the button's background colour is gray, it sets it to blue, or if the background colour is blue, it sets it to gray. You can replace the UIColor.BlueColor() or UIColor.GrayColor(), with a more personalised UIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) if you want.

Edit: If you just want to change text colour of the button, just add this statement or its variations in the required place:

button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Selected)

Solution 2

Use this method of UIButton class

func setTitleColor(_ color: UIColor?,
          forState state: UIControlState)

The state you are looking for is .Selected

And of course you have to handle selected state by yourself as a toggle button is not a native behavior.

Solution 3

For Swift 3:

// for change background color of a selected button in a collection view
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let collectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
    collectionCell.button.addTarget(self, action: #selector(button_Select(_:)), for: .touchUpInside) // add target for action

    return collectionCell
}

@objc func button_Select(_ sender: UIButton) {
    if sender.isSelected == true {
        sender.backgroundColor = UIColor.uicolorFromHex(0x262D35, alpha: 100)
        sender.setTitleColor(UIColor.white, for: .normal)
        sender.isSelected = false
    } else {
        sender.backgroundColor = UIColor.uicolorFromHex(0xF3CD70, alpha: 100)//Choose your colour here
        sender.setTitleColor(UIColor.white, for: .normal) //To change button Title colour .. check your button Tint color is clear_color..
        sender.isSelected = true
    }
}

without CollectionView:

 //MARK: - UIButton Action
  @IBAction func colorChangingBtn(_ sender: UIButton){
      sender.isSelected = !sender.isSelected
      if sender.isSelected{
        sender.backgroundColor = UIColor.gray
        sender.setTitleColor(UIColor.blue, for: .normal)
         }
      else{
        sender.backgroundColor = UIColor.blue
        sender.setTitleColor(UIColor.white, for: .normal)
       }
   }
Share:
40,827
Admin
Author by

Admin

Updated on July 18, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm trying to make a basic app my iPhone. I'm completely new to Xcode and I've had a browse on google and could not find exactly what I'm looking for. I'm trying to make a checklist for my plane.

    I've basically got a View controller with several buttons on. And what I want is for the button to change from grey to blue once pressed and stay blue unless pressed again. I have no knowledge of Xcode and Swift language at all so if anyone could help please explain as if you're explaining to a kid.

    So far I've managed to get the pages all setup and scrolling working but I just need the buttons to change now.

    Thank you in advance, Ty.

  • dziobaczy
    dziobaczy over 3 years
    when user holds the finger on button the state would be .highlighted, example: button.setTitleColor(UIColor.white.withAlphaComponent(0.5), for: .highlighted)