Change UIButton image on click

Mohammed Drame
2 min readDec 16, 2019

Change image on UIButton when click

This what you trying to do?

Github repo

Code explanation at the bottom:

import UIKitclass ViewController: UIViewController {// ---------------------------------- //
// - - - - - - - VARS - - - - - - - //
// ---------------------------------- //
var isOn: Bool = false// ---------------------------------- //
// - - - - - - - OUTLETS - - - - - - //
// ---------------------------------- //
// ---------------------------------- //
// - - - - - - - ACTION - - - - - - - //
// ---------------------------------- //
@IBAction func buttonPress(_ sender: UIButton) {// "Use this method to toggle a Boolean value from true to false or from false to true." [ Apple Doc ]isOn.toggle()// call Button functionsetButtonBackGround(view: sender, on: imageLiteral(resourceName: "like"), off: imageLiteral(resourceName: "unlike"), onOffStatus: isOn)
}
// Button Function ( Can also add to custome class )func setButtonBackGround(view: UIButton, on: UIImage, off: UIImage, onOffStatus: Bool ) { switch onOffStatus {
case true:
// Chnage backgroundImage to hart image
view.setImage(on, for: .normal)
// Test
print("Button Pressed")
default:
view.setImage(off, for: .normal
print("Button Unpressed")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}

I try to make this code as object-oriented as possible. On line 17 we created a variable isOn of type Bool and set it to false. Line 32 we toggled that isOn variable in our buttonPress @IBAction function. What that does is change the isOne variable state ever time the button is click/press. Toggle as basically an on and off switch.

Line 41 we create a function call setButtonBackGround and give it four (4) parameters, view, on, off, and on-off status. A better name for the on, off parameter of our function would have been onImage, offImage. We later created a switch statement base on the onOffStatus parameter of our function. If our onOffStatus parameter is set to ON doing runtime, we assign the button image a property using the view parameter of our function. vice versus.

Lastly, on line 34 we call the setButtonBackGround function in our buttonPress function and pass in the arguments. Voilà.

--

--