Update UIButton image using Swift 2.0

1.2k Views Asked by At

When I try using this solution to update an UIButton image (Xcode 7 beta 1), it gives me this error

Cannot invoke 'setImage' with an argument list of type '(UIImage?, forState: nil)'

Here's the code:

if counter % 2 == 0{
    playButton.setImage(UIImage(named: "pause"), forState: nil)
}
else if counter % 2 == 1 {
    playButton.setImage(UIImage(named: "play"), forState: nil)
}

How can I fix this?

2

There are 2 best solutions below

0
On BEST ANSWER

The forState argument cannot be nil - It has to be a UIControlState.

In your case, you should use UIControlState.Normal

if counter % 2 == 0{
    playButton.setImage(UIImage(named: "pause"), forState: UIControlState.Normal)
}
else if counter % 2 == 1 {
    playButton.setImage(UIImage(named: "play"), forState: UIControlState.Normal)
}
0
On

Here we can replace UIControlState.Normal with .Normal (Both will work Fine Better to use .Normal because this will be swift short hand feature)

if counter % 2 == 0{
    playButton.setImage(UIImage(named: "pause"), forState: .Normal)
}
else if counter % 2 == 1 {
    playButton.setImage(UIImage(named: "play"), forState: .Normal)
}