I am trying to create a toggle button for each cell in my table. When pressed, it will change the image and when pressed again it will change the image again -- Toggle.
Swift 4.0 Solution (using Storyboards)
First, ensure the UIButton
Type is set to Custom
in the Attributes Inspector.
// Reference to UIButton in Storyboard
@IBOutlet weak var toggleButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// assumes you have two images in the bundle/project
// called normal.png and selected.png.
let normalImage = UIImage(named: "normal.png")
let selectedImage = UIImage(named: "selected.png")
toggleButton.setImage(normalImage, for: .normal)
toggleButton.setImage(selectedImage, for: .selected)
}
Below screenshot demonstrates reference to toggleButton
in Storyboard, and Touch Up Inside
Event, ie: a user tapping the button, which fires off didPressButton
below.
@IBAction func didPressButton(_ sender: Any) {
// if the button was selected, then deselect it.
// otherwise if it was not selected, then select it.
toggleButton.isSelected = !trackingButton.isSelected
if toggleButton.isSelected {
print("I am selected.")
} else {
print("I am not selected.")
}
}