Search code examples
swiftuibuttonuipickerview

Condition not being triggered on first pick of pickerView


I have a button and pickerView. When the button is pressed, the pickerView is displayed.

Once a selection is made on the pickerView, the title of the button should change to "Show All", which it does, but never on the first iteration. It only changes on subsequent button presses.

I'm sure I've missed something, but can't put my finger on what.

@IBOutlet weak var chooseSourcesBtnOut: UIButton!
var isPicky = false  

@IBAction func chooseSourcesBtn(_ sender: UIButton) {
isPicky = !isPicky    

if isPicky {
  if self.dropDown.isHidden {
    self.dropDown.isHidden = false
  }
} else {
  if self.dropDown.isHidden == false {
    self.dropDown.isHidden = true
  }
  chooseSourcesBtnOut.titleLabel?.text = "Choose Source"
  tableView.reloadData()
}
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    isPicky = true
    selection = pickerSourceRows[row]    
    chooseSourcesBtnOut.titleLabel?.textAlignment = .center
    chooseSourcesBtnOut.titleLabel?.text = "Show All"
    dropDown.isHidden = true
    tableView.reloadData()
  }

Solution

  • I moved the line setting the text alignment to center to viewWillAppear and it works as intended now. Apparently it's a no-no to change the textAlignment of a button, then immediately change the text. Who knew? Oh well, that belonged in viewWillAppear for all intents and purposes anyway.

    override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(true)
       chooseSourcesBtnOut.titleLabel?.textAlignment = .center
    }