Search code examples
iosswiftuipickerviewviewdidload

PickerView Default row selected but returns zero unless the picker view is moved


In my picker view I want the default row to be zero. This row has a value of 1. I want to be able to touch nothing on the view contoller except a button. I know there are similar questions but they did not work for me.

override func viewWillAppear(_ animated: Bool) {

    self.pickerView.delegate = self
    self.pickerView.dataSource = self


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

      }


func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return String(numbers[row])
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return numbers.count

}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

     therow = pickerView.selectedRow(inComponent: 0) + 1        
}

then

@IBAction func submitTapped(_ sender: Any) { Print (therow) }

When I tap submit and print the value at row 0 it is 0, but if I wiggle the picker view and put it back on row 0 then it prints 1. I need to be able to touch nothing on the picker view and have it return the proper value of the default row.


Solution

  • You should use the row that the pickerview delegate method gives you , so you should modify your code as follows:

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    
         therow = numbers[row]   
         //theRowIndex = row   //this is the index of row that you selected
    
    
    }
    

    e.g if numbers array is numbers = [1, 2, 3, 4], when you click on first row above code will set therow to be 1 and if you click on second row, it will set therow to be 2 and so on.

    if you want to use the code that you wrote then you can use as follows:

    therow = numbers[pickerView.selectedRow(inComponent: 0)]
    

    this will give you the number for selected row , but I think you dont need it inside the above method.

    Now if you dont want to touch the picker then I think you need to do this:

    @IBAction func submitTapped(_ sender: Any) { 
           therow =  numbers[self.pickerView.selectedRow(inComponent: 0)]
           print(therow)
    
     }