Reputation: 45
Im simply trying to make it so when I click on a UIButton (for which it currently shows the image of a shell), the image changes into something else (in this case, a coin). This is what i tried so far and have not had any success. I cant find anything to do this for Swift.Thanks.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lblOutput: UILabel!
@IBOutlet weak var lblWin: UILabel!
@IBOutlet weak var lblLost: UILabel!
@IBOutlet weak var lblWinsAmt: UILabel!
@IBOutlet weak var lblLossesAmt: UILabel!
let coin = UIImage(named: "penny_head") as UIImage;
override func viewDidLoad() {
super.viewDidLoad()
//imgShell1.hidden = true //doesnt work
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnStart(sender: UIButton) {
}
@IBAction func btnShell1(sender: UIButton) {
sender.setImage(coin,forState: UIControlState.Highlighted);
}
Upvotes: 2
Views: 20452
Reputation: 16141
You can also use isSelected
.
button.setImage(image2, for: .normal)
button.setImage(image1, for: .selected)
Upvotes: 0
Reputation: 314
If you are looking to change the UIButton
's background image permanently you have to use Antonio's method:
sender.setImage(coin,forState: UIControlState.Normal)
This won't change the UIKit
's default highlighting when you tap the button. When you don't want the button to be highlighted when you touch it or have different appearances for different states, then you might be better off using an UIImageView
.
In viewDidLoad()
:
imgView?.image = imgOne
imgView?.userInteractionEnabled = true
imgView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "changeImage:"))
The function that changes the image:
func changeImage(recognizer: UITapGestureRecognizer){
self.imgView?.image = imgTwo
}
Upvotes: 0
Reputation: 1923
The way you're setting up the control is incorrect. Assuming you have a button property named btnShell
(and it's the button you want to setup) change your viewDidLoad() method to:
override func viewDidLoad()
{
super.viewDidLoad()
btnShell.setImage(imgShell1, forState:.Normal);
btnShell.setImage(coin, forState:.Highlighted);
}
And then remove the setImage(_:forState:) call from the action method:
@IBAction func btnShell1(sender: UIButton) {
sender.setImage(coin,forState: UIControlState.Highlighted);
}
Upvotes: 7
Reputation: 72750
To permanently change the button image on tap, you have to use the .Normal
enum case and not .Highlighted
for the control state:
sender.setImage(coin,forState: UIControlState.Normal)
Setting the image for the .Highlighted
state makes the new image appear only when the button is in that state, i.e. when it is tapped.
Upvotes: 4