Default Picker Value iphone

余生颓废 提交于 2019-12-11 10:53:26

问题


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!


回答1:


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;
}



回答2:


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



来源:https://stackoverflow.com/questions/1625880/default-picker-value-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!