Question

Is there a way to set a default value for a picker? I save the last selected row from all the pickers and I want to be able to have the pickers load those saved rows at start up. As of now I have found this code:

[settingsPagePicker selectRow:3 inComponent:0 animated:YES];

It works but only when the user taps the picker. I need it to work when the app is first loaded. If I put this code at viewDidLoad the app will crash. Anyone know where the proper place to put this in my code to make it work?

Thank you for your time!

Was it helpful?

Solution

Have you checked your data source for the settingsPagePicker before calling -selectRow:inComponent:animated to make sure there is data available at that index (3 in your sample code)?

How are you loading your data for your data source? You can initialize your data source in viewDidLoad first and then call selectRow once you know there is data available.

UPDATE: Here is what your code should look like or something like it:

- (void)viewDidLoad
{
    [super viewDidLoad];
    pickerDataSource = [[NSMutableArray alloc] init];
    [pickerDataSource addObject:@"Item 01"];
    [pickerDataSource addObject:@"Item 02"];
    [pickerDataSource addObject:@"Item 03"];
    [pickerDataSource addObject:@"Item 04"];

    // Might want to move this to -viewWillAppear:animated
    [settingsPagePicker selectRow:3 inComponent:0 animated:YES];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView == settingsPagePicker)
    {
        return [pickerDataSource objectAtIndex:row];
    }
    return @"";
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component 
{
    if (pickerView == settingsPagePicker)
    {
        return [pickerDataSource count];
    }
    return 0;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView
{
    return 1;
}

OTHER TIPS

Here some methods from my class.

- (void)viewDidLoad {
   [super viewDidLoad];
   currentNumbersOfComponents = 1;
   //[picker selectRow:2 inComponent:0 animated:NO];
}
- (void) viewDidAppear:(BOOL)animated{
   [super viewDidAppear:animated];
   [picker selectRow:2 inComponent:0 animated:YES];
}

#pragma mark picker view data source methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return currentNumbersOfComponents;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return 5;
}

picker.dataSource is self

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top