How To Change UI Button Image In Swift Programmatically

Changing a button’s image, for example from a pause sign to a play sign, is a common task for iOS devs.

How To Change UI Button Image Swift Programmatically

Assuming your button is called playPauseButton and you have an UIImage named image you can do this:

playPauseButton.setImage(image, forState: .normal)

If you need to load the image from your assets, it’s best to do it safely in a if let statement

if let image = UIImage(named: "pause") {
    playPauseButton.setImage(image, for: .normal)
}

Of course you can just define the image in the same line if you want:

playPauseButton.setImage(UIImage(named: "pause"), for: .normal)
If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts