Shahin
Shahin

Reputation: 81

How to change UIButton's image every time it is pressed

How can I make a UIButton change image from A to B and again B to A, every time it's pressed?

Not as .normal to .highlighted, but permanent. I've tried the .highlighted method because I can't find the code for permanent, here's my code:

func ChangeButton() {
    Button.setImage(A, for: .normal)
    Button.setImage(B, for: .highlighted)

Upvotes: 0

Views: 3121

Answers (2)

Xavier L.
Xavier L.

Reputation: 747

I recommend changing the backgroundImage because it's scaled automatically, and the button text in front won't get covered.

If it's a custom button, within its initializer:

self.addTarget(self, action: #selector(*yourfunctoswitchimages*), for: .touchUpInside)

... and then that yourfunctoswitchimages can just check what the current background image is, and switch it accordingly.


If it's not a custom button, add a target to it in viewDidLoad or something. Here's a lot of sample code.

In your viewDidLoad()

yourButt.addTarget(self, action: #selector(switcheroo), for: .touchUpInside)

Another func in your view controller:

func switcheroo() 
{
    if yourButt.currentBackgroundImage == image1
    { 
        yourButt.setBackgroundImage(image2), for: .normal)
    }
    else { // ...set image to image1 }
}

yourButt would be a property of your view controller of course, that way it's accessible to the viewDidLoad() and to other funcs within it.

Upvotes: 0

Aleksey Potapov
Aleksey Potapov

Reputation: 3783

Thanks for mentions of setBackgroundImage to Xavier L. from the other answer. Try the following code:

import UIKit
class ViewController: UIViewController {

    @IBOutlet var button: UIButton!
    var buttonActive = false

    override func viewDidLoad() {
        super.viewDidLoad()
        button.setBackgroundImage(UIImage(named: "apple"), for: .normal)
    }

    @IBAction func buttonPressed() {
        if buttonActive {
            button.setBackgroundImage(UIImage(named: "apple"), for: .normal)
        } else {
            button.setBackgroundImage(UIImage(named: "pineapple"), for: .normal)
        }
        buttonActive = !buttonActive
    }
}

And your storyboard should look like that: Storyboard

N.B. On Stack Overflow you should perform some actions before asking. Try to include some code you tried.

Upvotes: 1

Related Questions