Search code examples
swiftxcodeswift4uipickerviewxcode9

Swift 4 hidden buttons not reappearing


This is a follow up to my previous question here. I was able to get the buttons to hide just fine but they don't reappear when I select the college education option. Here is my code:

@IBOutlet weak var eduField: UITextField!   
var education = ["Middle School Education", "High School Education", "College Education"]   
var eduPicker = UIPickerView()

@IBOutlet weak var associate: UIButton!

@IBOutlet weak var bachelor: UIButton!

@IBOutlet weak var master: UIButton!
override func viewDidLoad() {
    super.viewDidLoad()
    eduPicker.delegate = self
    eduPicker.dataSource = self
    eduField.inputView = eduPicker

    if eduField.text == "College Education"{
      associate.isHidden = false
      bachelor.isHidden = false
      master.isHidden = false
    }
    else{
      associate.isHidden = true
      bachelor.isHidden = true
      master.isHidden = true
  }
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return education.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    eduField.text = education[row]
    eduField.resignFirstResponder()
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return education[row]
    }
}

I know that my code is partially correct as these buttons hide or appear is I change the values in else from false to true but I guess I don't fully understand how the values are stored in the viewpicker as my code obviously doesn't recognize the values I tell it to. I feel really dumb asking about roughly the same issue twice in a twenty-four hour period but, this is driving me insane. Can someone please help me?


Solution

  • Looks like you are not updating your buttons statuses.

    I'd suggest having a method like:

    func updateButtonsVisibility() {
        if eduField.text == "College Education"{
          associate.isHidden = false
          bachelor.isHidden = false
          master.isHidden = false
       } else {
           associate.isHidden = true
           bachelor.isHidden = true
           master.isHidden = true
       }
    }
    

    And then call that same method both in viewDidLoad() and at the end of func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int).