Search code examples
iosswiftxcodecocoa-touchuibutton

How to change UIButton image in Swift


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

Solution

  • 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)