问题
I have pickerView with two rows and I need to save position of both to NSUserDefaults. I have successful saved first row with this code:
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSInteger selectedRow = [thePickerView selectedRowInComponent:0];
[[NSUserDefaults standardUserDefaults] setInteger:selectedRow forKey:@"picker"];
}
And I don't get how to add a second one.
With this code I bring back the position:
-(void)viewWillAppear: (BOOL) animated {
NSUserDefaults *pickerViewSelectionDefaults = [NSUserDefaults standardUserDefaults];
[picker selectRow:[pickerViewSelectionDefaults integerForKey:@"picker"] inComponent:0 animated:YES];
[picker selectRow:[pickerViewSelectionDefaults integerForKey:@"picker"] inComponent:1 animated:YES];
}
回答1:
Try this:
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component {
NSInteger selectedRow = [thePickerView selectedRowInComponent:component];
NSString *key = [NSString stringWithFormat:@"picker%d", component];
[[NSUserDefaults standardUserDefaults] setInteger:selectedRow forKey:key];
}
and this
-(void)viewWillAppear: (BOOL) animated {
NSUserDefaults *pickerViewSelectionDefaults = [NSUserDefaults standardUserDefaults];
[picker selectRow:[pickerViewSelectionDefaults integerForKey:@"picker0"]
inComponent:0 animated:YES];
[picker selectRow:[pickerViewSelectionDefaults integerForKey:@"picker1"]
inComponent:1 animated:YES];
}
回答2:
Add them with separate keys.
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component {
NSInteger selectedRow = [thePickerView selectedRowInComponent:0];
[[NSUserDefaults standardUserDefaults] setInteger:selectedRow forKey:@"pickerRow1"];
[[NSUserDefaults standardUserDefaults] setInteger:selectedRow forKey:@"pickerRow2"];
}
来源:https://stackoverflow.com/questions/6034276/how-can-i-save-a-second-row-of-uipickerview-to-nsuserdefaults