Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

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.

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top