Reputation: 11
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
Upvotes: 0
Views: 1041
Reputation: 72410
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.
Upvotes: 1
Reputation: 706
You need to assign two images for the button like the screenshots below.
As you can see I have state config as Default and Selected.
Later on the action of button you can do
@IBAction btnTapAction(sender: UIButton) {
if sender.selected{
sender.selected = false
}
else{
sender.selected = true
}
}
Upvotes: 1