Mi Ch Mi Ch - 5 months ago 20
Swift Question

Animation on button image when tapped

I'm new to Swift and to stackoverflow so please comment for any improvements. I can make to my asking of questions!

I have created a

UIButton
that has an image. When tapped, the image is supposed to change to another image. Currently, once tapped, it 'flashes' with the image it is supposed to change to and then immediately changes back to the original image.

I created an outlet:

@IBOutlet var buttonImage: UIButton!


Then I added this:

override func viewDidLoad() {
super.viewDidLoad()
//Change image.

buttonImage.setImage(UIImage(named:"image1.png"),forState:UIControlState.Normal)
buttonImage.setImage(UIImage(named:"image2.png"),forState:UIControlState.Highlighted)

}


Help is gratefully received.

EDIT - added error screenshot.errorscreenshot

Answer

You need to change your viewDidLoad code like this

buttonImage.setImage(UIImage(named:"image1.png"),forState:UIControlState.Normal)
buttonImage.setImage(UIImage(named:"image2.png"),forState:UIControlState.Selected)

Now change you IBAction like this

@IBAction func btnTap(sender: UIButton) {
    sender.selected = !sender.selected
}

Hope this will help you.

Comments