0

Hey I'm new in iOS Development, I have a problem to make two button selected and unselected state and then store value of a gender. I want when user choose gender the other gender will be disable. Can anyone help me?

My button code

let menButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Men", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.backgroundColor = .yellow
    button.isSelected = false
    button.isEnable = true
    button.addTarget(self, action: #selector(handlePickGender), for: .touchUpInside
    return button
}()

let womenButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Women", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.backgroundColor = .blue
    button.isSelected = false
    button.isEnable = true
    button.addTarget(self, action: #selector(handlePickGender), for: .touchUpInside
    return button
}() 
AlexSmet
  • 2,141
  • 1
  • 13
  • 18
ferryawijayanto
  • 569
  • 4
  • 18
  • This should help https://stackoverflow.com/questions/25524638/disable-a-button – IMACODE Oct 19 '18 at 09:29
  • By making a button disabled, do you mean to say that you need to update the color or text of the buttons to **show** this change, while the button that's not selected should still be available for selection? – D V Oct 19 '18 at 09:42

3 Answers3

0

First, create enum for Gender and add the Male and Female as the cases for that enum.

enum Gender {
  case male
  case female
 }

Have the switch for toggling the UIButton states.

func chooseGender(_ gender: Gender) {

   switch gender {
     case .male:
        // code for select and unselect
     case .female:
        // code for select and unselect
    }
}

From the UIButton, use the isEnabled property for enable and disable.

0

If you are trying to create toggle buttons.

you can set button image for state.

button.setImage(UIImage(named: "unselected"), for: .normal)
button.setImage(UIImage(named: "selected"), for: .selected)


@IBAction func buttonPressed(sender: UIButton) {
    button.selected = !button.selected
}

OR you can set background color for button

@IBAction func buttonPressed(sender: UIButton) {
        button.selected = !button.selected
        if button.selected {
             button.backgroundColor = .blue
        } else {
             button.backgroundColor = .clear
        }
}
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
0

try this:

@objc func handlePickGender(sender: UIButton) {
        menButton.setTitleColor(UIColor.yellow, for: .normal)
        womenButton.setTitleColor(UIColor.yellow, for: .normal)
        sender.setTitleColor(UIColor.blue, for: .normal)
        //store gender
        let selectedGender = sender.title(for: .normal)
   }
Sujit Nachan
  • 204
  • 1
  • 8