iPhone的默认选择器值 [英] Default Picker Value iphone

查看:87
本文介绍了iPhone的默认选择器值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为选择器设置默认值?我保存了所有选择器中最后选择的行,并且希望能够让选择器在启动时加载那些保存的行.到目前为止,我已经找到以下代码:

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

它有效,但仅在用户点击选择器时有效.首次加载应用程序时,我需要它工作.如果我将此代码放在viewDidLoad上,应用程序将崩溃. 有谁知道将其放置在我的代码中的适当位置以使其起作用?

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?

谢谢您的时间!

推荐答案

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

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)?

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

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

这篇关于iPhone的默认选择器值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆