1

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.

Michael R.
  • 25
  • 9

3 Answers3

2

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)

 }
3stud1ant3
  • 3,586
  • 2
  • 12
  • 15
1

Use this statement once you load your picker view with data.

yourPicker.selectRow(0, inComponent:0, animated:true)

You can change the default selected value by changing the first parameter of selectRow.

Nupur Gupta
  • 305
  • 1
  • 12
1

I think the reason why this happens is that didSelectRow is somehow not called if you selected the row programmatically. As per the docs:

Called by the picker view when the user selects a row in a component.

So you need to set your therow property programmatically after you call selectRow:

self.pickerView.selectRow(0, inComponent: 0, animated: true)
therow = 1 // <--- this line
Sweeper
  • 213,210
  • 22
  • 193
  • 313