0

我有一个带有休闲 viewDidLoad 的 ViewController:

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

这个 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];
}

问题是,在 viewDidLoad 中,当我设置 row = 8 时,它总是不会选择最后一行 - 而是倒数第二行(而不是“Sport - Leistungssport”,它选择“Sport - Ausdauersport”)。当我使用小于 8 的行时,它将正常工作。

有人可以帮助我吗,我做错了什么?- 谢谢。

4

3 回答 3

3

这是带有自动布局的 iOS 6 中的一个错误。我能想到的唯一解决方法是禁用自动布局或在 viewDidAppear 中设置选择器选择:而不是 viewDidLoad 或 viewWillAppear:。

有关更多信息,请参阅以下内容: UIPickerView can't autoselect last row when compiled under Xcode 4.5.2 & iOS 6

于 2013-06-23T20:43:14.307 回答
0

据我所知,

你的数组中有 9 个对象。

数组的索引为 0 到 n-1(在您的情况下为 0 到 8,而不是 1 到 9)

它选择了正确的行,你没有设置正确的索引。

如果你想让它选择倒数第二个,即使数组中的字符串/对象的数量不同,只需将其设置为

int row = [programTypes count]-2; //[programTypes count]-1 is the last row.
于 2013-06-23T17:10:47.573 回答
0

在您的代码片段中,变量 programTypes.count 返回计数为 9,您将 selectedRow 设置为 8,以便选择器选择最后一行。

于 2013-06-23T17:12:27.967 回答