47

By default the first row is highlighted after initializing the UIPickerView. How do i highlight a particular row or scroll to particular row programmatically?

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
pradeepa
  • 4,104
  • 5
  • 31
  • 41

5 Answers5

76

As always, this is thoroughly documented. The Apple documentation for UIPickerView should tell you that the method you probably want is – selectRow:inComponent:animated:.

warrenm
  • 31,094
  • 6
  • 92
  • 116
  • 6
    If anyone can't find it in Xamarin.iOS (MonoTouch) it is called `Select()` not `SelectRow()` like you would think. – Alex Wiese Jul 12 '13 at 05:41
  • For me calling the `- selectRow:inComponent:animated:` method was not enough, I had to call the delegate `-pickerView:didSelectRow:inComponent:` programmatically too. – fruechtemuesli Feb 17 '15 at 10:17
  • Right; programmatically setting the selected row doesn't invoke the delegate method. If you want to take action in response to all selection changes, you have to call it yourself. – warrenm Feb 17 '15 at 17:30
45

If you want to trigger delegate's method pickerView:didSelectRow:inComponent, you should call it manually:

Obj-C

[self.myPickerView selectRow:0 inComponent:0 animated:NO];
[self pickerView:self.myPickerView didSelectRow:4 inComponent:0];

Swift

self.myPickerView.selectRow(0, inComponent: 0, animated: false)
self.pickerView(self.myPickerView, didSelectRow: 0, inComponent: 0)
Thomás Pereira
  • 9,589
  • 2
  • 31
  • 34
35

Yes, it's very easy [picker selectRow:row inComponent:component animated:NO];

Rich
  • 1,082
  • 7
  • 11
3

Working in iOS 9 with XCode 7.3, to make runtime changes to data in a picker view called fieldPicker:

// first load your new data to your picker view's data source (not shown here...) then load the data into the picker view using it's delegate
    [self.fieldPicker reloadAllComponents];

    // now that the data is loaded, select a row in the picker view through it's delegate
    [self.fieldPicker selectRow:([self.theFields count] - 1) inComponent:0 animated:NO];

// retrieve the row selected in the picker view to use in setting data from your data source in textboxes etc.
    long row = (long)[self.fieldPicker selectedRowInComponent: 0];
Spanky
  • 4,980
  • 7
  • 36
  • 37
1

Check if you call the method self.myPickerView.selectRow(0, inComponent: 0, animated: false) after you added the pickerView as a subview.

First, I called the method before I added the pickerView as a subview and it did not work. Therefore, I called it afterwards and then it worked!

Probably pretty obvious and not my smartest move but still maybe someone has the same problem some day and I hope I could help! :)

Mitemmetim
  • 520
  • 3
  • 12