How to change UIButton image in Swift
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)
}
}
assume that this is your connected UIButton Name
like
@IBOutlet var btn_refresh: UIButton!
your can directly place your image in three modes
// for normal state
btn_refresh.setImage(UIImage(named: "xxx.png"), forState: UIControlState.Normal)
// for Highlighted state
btn_refresh.setImage(UIImage(named: "yyy.png"), forState: UIControlState.Highlighted)
// for Selected state
btn_refresh.setImage(UIImage(named: "zzzz.png"), forState: UIControlState.Selected)
on your button action
//MARK: button_refresh action
@IBAction func button_refresh_touchup_inside(sender: UIButton)
{
//if you set the image on same UIButton
sender.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal)
//if you set the image on another UIButton
youranotherbuttonName.setImage(UIImage(named: "newimage.png"), forState: UIControlState.Normal)
}
Swift 5
yourButton.setImage(UIImage(named: "BUTTON_FILENAME.png"), for: .normal)