Reputation: 6259
I have a ViewController with the fallowing viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
model = [GlobalDataModel sharedDataModel];
programTypes = @[@"Gewichtsreduktion", @"Verdauungs-/Stoffwechselprobleme", @"Energielosigkeit, Müdigkeit",
@"Stress, Burn-out", @"Unruhe, Schlaflosigkeit", @"Immunsystem, Hautprobleme", @"Sport - Muskelaufbau", @"Sport - Ausdauersport", @"Sport - Leistungssport"];
int row = 8; //[model.infoDictionary[@"programmtyp"] intValue];
[programTypePicker selectRow:row inComponent:0 animated:NO];
}
and this delegate-methods for the UIPickerView:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return programTypes.count;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
forComponent:(NSInteger)component {
return programTypes[row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
model.infoDictionary[@"programmtyp"] = [NSString stringWithFormat:@"%ld",(long)row];
}
The problem is, that in the viewDidLoad, when I set row = 8 it will always select not the last row - instead the second-last row (instead of "Sport - Leistungssport" it select "Sport - Ausdauersport"). When I use a row smaller then 8 it will work correctly.
Does somone can help me, what I am doing wrong? - Thank you.
Upvotes: 0
Views: 2660
Reputation: 411
This is a bug in iOS 6 with autolayout. The only workarounds I could figure out were to disable autolayout or set the picker selection in viewDidAppear: instead of viewDidLoad or viewWillAppear:.
See the following for more info: UIPickerView can't autoselect last row when compiled under Xcode 4.5.2 & iOS 6
Upvotes: 3
Reputation: 12239
In your code snippet the variable programTypes.count returns count as 9 and you set the selectedRow as 8 so the picker selects the last before row.
Upvotes: 0
Reputation: 5812
From what I could figure,
you have 9 objects in your array.
Arrays are indexed 0 to n-1 (in your case 0 to 8, not 1 to 9)
its selecting the correct row, you are not setting the right index.
If you want to make it select the second last even if the number of strings/objects in the array vary, just set it to
int row = [programTypes count]-2; //[programTypes count]-1 is the last row.
Upvotes: 0