默认选择器值iphone

时间:2009-10-26 16:48:52

标签: iphone default default-value picker

有没有办法为选择器设置默认值?我从所有选择器中保存了最后选择的行,我希望能够在启动时让选择器加载这些保存的行。截至目前,我已找到此代码:

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

只有当用户点击选择器时它才有效。首次加载应用时,我需要它才能工作。如果我将此代码放在viewDidLoad上,应用程序将崩溃。 任何人都知道在我的代码中放置它的适当位置,以使其工作?

感谢您的时间!

2 个答案:

答案 0 :(得分:6)

在调用-selectRow之前,您是否检查过settingsPagePicker的数据源:inComponent:animated以确保该索引处有数据可用(示例代码中为3)?

如何为数据源加载数据?您可以先在viewDidLoad中初始化数据源,然后在知道有可用数据后调用selectRow。

更新:这是您的代码应该是什么样的或类似的东西:

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

答案 1 :(得分:2)

这是我班上的一些方法。

- (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是self