Search code examples
iossettingsuipickerviewnsuserdefaults

How to Set the UIPickerView Initiated Row?


I'm using UIPickerView in my app. I used some tutorials to do the settings and to take the selected data from the user, and it's working fine.

What I'm not clear about is how to tell the UIPickerView, when it's initiated with data (using - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component), to point at a certain value.

To be more specific:

  • I have a UIPickerView that holds an array of NSStrings
  • Once the user selects a value I get it and keep it via NSUserDefaults
  • When the user gets back to the UIViewController that holds the UIPickerView, I want to get the saved data from NSUserDefaults and have the UIPickerView point to the value that was saved there.

Where should I write the code that sets this data?


Solution

  • You would write it on ViewWillAppear: (because this is when you want to set the data).

    There you can read the value from you model (Core Data, NSUSerDefaults, Plist, etc.) and set it using:

    - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
    

    This is a method of the UIPickerView.