Reputation: 9
I am new to iOS app development using Swift 4. I used the code below to change the image of button2
by running it in the iOS simulator:
@IBAction func button2(_ sender: Any) {
button2.setImage(UIImage(named: "wrong_answer"), for: .normal)
}
However, button2
was highlighted when I first click on it without changing its image. Then after the second click, the image has been changed in button2
.
My question is why the image was not changed in button2
after the first click?
What can I do to change the image after the first click instead of twice? Is this a bug in the iOS simulator of Xcode or it is normal?
Upvotes: 0
Views: 648
Reputation: 9
it's simulator bug. it worked on a real device @IBAction func button2(_ sender: UIButton) { button2.setImage(UIImage(named: "wrong_answer"), for: .normal) }
Upvotes: 0
Reputation: 5303
Rename your method/action so it differs from the button/property.
Change Any to UIButton since you know its class.
@IBAction func buttonTapped(_ buttonTapped: UIButton) {
buttonTapped. button.isSelected = !button.isSelected
}
Make sure that you are receiving the button callbacks by declaring your view controller a UIButtonDelegate and set the button's delegate property to self.
Upvotes: 0
Reputation: 1389
You probably have an issue related to UIButton
states that is causing this problem.
I don't think it is a simulator bug.
By the way, a good practice you should follow is to name the outlet different than the @IBAction
. Let's say:
@IBAction func buttonTapped(_ sender: Any) {
button.setImage(UIImage(named: "image"), for: .normal)
}
Try this:
override func viewDidLoad() {
super.viewDidLoad()
button.setImage(UIImage(named: "image"), for: .selected)
}
@IBAction func buttonTapped(_ sender: Any) {
button.isSelected = !button.isSelected
}
And then the image will be updated automatically when you tap on the button. You can change it to button.isSelected = true
if you want to keep the image after the first tap.
Upvotes: 2