How to change UIButton image in Swift

Lop Hu picture Lop Hu · Nov 10, 2014 · Viewed 242.4k times · Source

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];

Answer

Dharmesh Kheni picture Dharmesh Kheni · Nov 10, 2014

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)