Part way done with learning swift but I hit a small wall and yet again, I'm sure I'm just a bit new at this and an easy solution is there but I'm having trouble figuring out how to select/deselect buttons below is what I have so far and it is a button turns into a checkmark when clicked on... I've gotten that far but I need that button to deselect when clicked on again and then obviously be able to be clicked again if need be.
@IBAction func buttonPressed(sender: AnyObject) {
sender.setImage(UIImage(named: "Checkmark.png"), forState: .Normal)
}
Swift 3 note: .selected
and .checked
are now lower case UIControlState
values in the SDK, and some of the methods have been renamed:
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), for: .normal)
button.setImage(UIImage(named: "Checked"), for: .selected)
You can also now use image literals with Xcode 8 instead of UIImage(named:)
:
#imageLiteral(resourceName: "Unchecked")
Swift 2:
Why not use the .Selected
state of the button as the "checked" state, and the .Normal
state as the "unchecked" state.
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), forState: .Normal)
button.setImage(UIImage(named: "Checked"), forState: .Selected)
// ...
@IBAction func buttonPressed(sender: AnyObject) {
if let button = sender as? UIButton {
if button.selected {
// set deselected
button.selected = false
} else {
// set selected
button.selected = true
}
}
}
You dont need to set selected in condition. I just doing with following method in swift:
func selectDeselect(sender: UIButton){
sender.selected = !sender.selected
if(sender.selected == true)
{
sender.setImage(UIImage(named:"select_heart"), forState: UIControlState.Normal)
}
else
{
sender.setImage(UIImage(named:"heart"), forState: UIControlState.Normal)
}
}
Here is Working code for swift 4.
Make Sure you need to connect Button IBAction
Outlet as UIButton
and set default button image from storyboard whatever you want.
@IBAction func btnTapped(_ sender: UIButton) {
if sender.currentImage == UIImage(named: "radio_unchecked"){
sender.setImage(UIImage(named: "radio_checked"), for: .normal)
}else{
sender.setImage(UIImage(named: "radio_unchecked"), for: .normal)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With