Search code examples
swiftuipickerview

Reset UIPickerview after use?


I have a UIPickerview that goes from 0-20. I want the users to be forced to select a int between 1 and 20. If the picker is on 0, an alert should pop up. The selection is confirmed with a button press, and same with the alert. I have done this:

pickerView.reloadAllComponents()
pickerView.selectRow(0, inComponent: 0, animated: true)    

This works fine one time. The picker return to 0, but if the next user forgets to select a number, the picker prints whatever the last user had selected, and not 0 that its actually showing.

How can I get the pickerView to understand that it has returned to 0?


Solution

  • You can set the variable used in didSelectRow to 0 when button is pressed.
    If you have:
    var chosenPickerViewNumber = Int()

    and to populate the pickerView you have:

    let pickerViewNumbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
        {
           chosenPickerViewNumber = pickerViewNumbers[row]
        }    
    

    You can simply do:

    @IBAction func yourButton(_ sender: UIButton){
         //Do stuff with the pickerView.    
          //Then:    
          chosenPickerViewNumber = 0   
        }