Dane Cameron
Dane Cameron

Reputation: 433

Swift - UIButton background colour does not change on click

I have a bit of code to play a sound effect when my button is clicked on. This works fine, so I tried adding in a background color change when the button is clicked but it doesnt seem to work (even though it shows no errors). what am I doing wrong?

What I decalred them as:

var soundEffectWhats: AVAudioPlayer = AVAudioPlayer()
var whatsup: UIButton = UIButton()

IBAction:

 @IBAction func whatsup(_ sender: Any) {
    soundEffectWhats.play()
    whatsup.backgroundColor = UIColor.blue}

Upvotes: 0

Views: 113

Answers (1)

Sean Stayns
Sean Stayns

Reputation: 4234

You should use

(sender as! UIButton).backgroundColor = UIColor.blue

instead of

whatsup.backgroundColor = UIColor.blue

to take care, that you get the right reference.

If you want to be carefully, you could use:

(sender as? UIButton)?.backgroundColor = UIColor.blue

but take care, that backgroundColor will only be executed, if the cast was successfully.

UPDATE: As Sulthan has mentioned in the comments, you can declare the sender as UIButton directly:

@IBAction func whatsup(_ sender: UIButton) {
    soundEffectWhats.play()
    sender.backgroundColor = UIColor.blue
}

Upvotes: 1

Related Questions