Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make two UIButtons perform like radio buttons in Swift?

I have two UIButtons that I want to use to set an A/B value to a variable before I save data to a database. I want a button to become selected when tapped, and deselected when the other button is tapped, and vice versa. What is a good solution for accomplishing this programmatically or in Interface Builder?

like image 371
Austin Berenyi Avatar asked Jan 30 '23 14:01

Austin Berenyi


2 Answers

In order to set an "A/B value" as you mention, the easiest option would be to use a UISwitch or -in the general case of possibly more than 2 options- a UISegmentedControl (as @rmaddy suggested in the question's comments) .

These controls have built-in the "choose just one out of many" functionality that you are looking for.

The drawbacks of the switch are:

  • It has to be either on or off (does not support a selection state of "neither A nor B")
  • You can't have separate title labels for each state.

If you still want two separate UIButton instances, you can:

  • Have references to both buttons in your view controller (@IBOutlets wired using Interface Builder), e.g.:

    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var rightButton: UIButton!
    
  • Implement the action method for both buttons in such a way that it sets the selected state of the tapped button, and resets the other one. For example:

    @IBAction func buttonAction(sender: UIButton) {
        if sender == leftButton {
            leftButton.isSelected = true
            rightButton.isSelected = false
        } else if sender == rightButton{
            leftButton.isSelected = false
            rightButton.isSelected = true
        }
    }
    

This is a quick-and-dirty solution for just two buttons. If you want a generic radio group of n-buttons, there are open source solutions on GitHub, etc...

like image 71
Nicolas Miari Avatar answered Feb 04 '23 04:02

Nicolas Miari


Try this.

First create both button separate @IBOutlet.

@IBOutlet weak var btnYes: UIButton!
@IBOutlet weak var btnNo: UIButton!

Set Both Button Tag Like this and you also set tag using storyboard.

override func viewDidLoad() {
      super.viewDidLoad()

    btnYes.tag = 1
    btnNo.tag = 2
}

Implement Common @IBAction method for both buttons

@IBAction func btnYesNoTapped(_ sender: UIButton) {
        if sender.tag == 1 {
            self.IsBtnSelected(isSelect: true, with: self.btnYes)
        }else {
            self.IsBtnSelected(isSelect: true, with: self.btnNo)
        }

}

Create Custome Method

func IsBtnSelected(isSelect:Bool,with sender:UIButton){
        self.btnYes.isSelected = false
        self.btnNo.isSelected = false
        sender.isSelected = isSelect
}
like image 28
Dixit Akabari Avatar answered Feb 04 '23 03:02

Dixit Akabari