Here is example how you can achieve that, let me know if you don't understand something.
class ViewController: UIViewController {
@IBOutlet weak var someBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
//Setting up images for normal and selected state.
func configureUI() {
let image = UIImage(named: "image")
let imageFilled = UIImage(named: "image-filled")
someBtn.setImage(image, for: .normal)
someBtn.setImage(imageFilled, for: .selected)
}
@IBAction func someBtnPressed(_ sender: Any) {
// Toggle basically makes someBtn’s selected state either true or false when pressed
someBtn.isSelected.toggle()
}
}
You can call setImage(_:for:)
method to set the image of the button for a particular state.
The button is at the normal
state when the user is not pressing it, so you should do:
yourButton.setImage(hollowHeart, for: .normal)
The button is at the highlighted
state when the user is touching it, so you should do:
yourButton.setImage(filledHeart, for: .highlighted)
You just need to do this once after you create the button, probably in viewDidLoad
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.