无法弄清楚如何为UIPickerView设置起始值

时间:2014-06-27 15:16:31

标签: ios

我使用UIPickerView并希望该部分相同,即上次使用时。我查看了Apple的文档,但没有看到关于设置部分的任何内容。

我的代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // Initialize Data
    _pickerData = @[@"I", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9"];

    // Connect data
    picker.dataSource = self;
    picker.delegate = self;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)aOk:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];

    // store data
    int i=0;
    i=[picker selectedRowInComponent:1]*10;
    i+=[picker selectedRowInComponent:1];
}
- (IBAction)aCancel:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}




// The number of columns of data
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

// The number of rows of data
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // compment contains the col number
    return _pickerData.count;
}

// The data to return for the row and component (column) that's being passed in
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return _pickerData[row];
}

// Catpure the picker view selection
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    // This method is triggered whenever the user makes a change to the picker selection.
    // The parameter named row and component represents what was selected.
}


@end

1 个答案:

答案 0 :(得分:0)

是的,我在开发Trivia游戏时遇到了同样的问题。以下是我解决问题的方法。

在您加载数据后,请使用此选择行:

UIPickerView * pickerView = [[UIPickerView alloc] initWithFrame:rect];
[pickerView setDelegate:self];
[pickerView setDataSource:self];
[view addSubview:pickerView];

//We're going to select a row with this line
[pickerView selectRow:[_pickerData objectAtIndex:0] inComponent:0 animated:YES];

我看到你说你希望pickerView默认为最后选择的行(我认为这是你想要说的话)?

如果是这种情况,我只会将最后选定的行存储在NSUserDefaults中(即使用户杀死应用程序也会保留该行)。

每当用户导航到选择器视图时,您可以执行以下操作:

NSInteger lastSelectedRow = [[NSUserDefaults standardUserDefaults] integerForKey:@"lastSelectedRow"];
if (lastSelectedRow)
    [pickerView selectRow:lastSelectedRow inComponent:0 animated:YES];
else
    [pickerView selectRow:[_pickerData objectAtIndex:0] inComponent:0 animated:YES];