Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 543
Lop Hu Avatar asked Oct 08 '22 17:10

Lop Hu


People also ask

How do I put the image on the right side of the text in a UIButton?

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.


3 Answers

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)
like image 368
Dharmesh Kheni Avatar answered Oct 28 '22 03:10

Dharmesh Kheni


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)
    }
}
like image 14
L.N.Vu Avatar answered Oct 28 '22 04:10

L.N.Vu


Swift 5

yourButton.setImage(UIImage(named: "BUTTON_FILENAME.png"), for: .normal)
like image 13
Antee86 Avatar answered Oct 28 '22 04:10

Antee86