Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select/deselect buttons swift xcode 7

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)
}
like image 509
yrpalnoob Avatar asked Nov 24 '15 23:11

yrpalnoob


3 Answers

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
        }
    }
}
like image 121
JAL Avatar answered Sep 28 '22 07:09

JAL


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)
        }

    }
like image 34
Nitin Gohel Avatar answered Sep 28 '22 08:09

Nitin Gohel


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)
    }
}
like image 22
Nikunj Kumbhani Avatar answered Sep 28 '22 07:09

Nikunj Kumbhani