I am trying to change the image of a UIButton using Swift... What should I do
This is OBJ-C code.but I don't know with Swift:
[playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
To make an UIButton's image align to the right side of the text, we force content flipping behavior to the one use it right-to-left language. 1 By adding this semanticContentAttribute = . forceRightToLeft , we force UIKit to mirrored our content which push our image to the right side of the text. Here is the result.
From your Obc-C code I think you want to set an Image for button so try this way:
let playButton = UIButton(type: .Custom)
if let image = UIImage(named: "play.png") {
playButton.setImage(image, forState: .Normal)
}
In Short:
playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
For Swift 3:
let playButton = UIButton(type: .custom)
playButton.setImage(UIImage(named: "play.png"), for: .normal)
in Swift 4, (Xcode 9) example to turn picture of button to On or Off (btnRec):
var bRec:Bool = true
@IBOutlet weak var btnRec: UIButton!
@IBAction func btnRec(_ sender: Any) {
bRec = !bRec
if bRec {
btnRec.setImage(UIImage(named: "MicOn.png"), for: .normal)
} else {
btnRec.setImage(UIImage(named: "MicOff.png"), for: .normal)
}
}
Swift 5
yourButton.setImage(UIImage(named: "BUTTON_FILENAME.png"), for: .normal)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With