2013-06-23 74 views
0

我有一個視圖控制器與休耕viewDidLoad中:UIPickerView不會選擇正確的行

- (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的行時,它會正常工作。

somone能幫助我,我做錯了什麼? - 謝謝。

回答

0

從我能想到的數字來看,

你有9個對象在你的數組中。

數組索引0到n-1(在你的情況下0-8,沒有1〜9)

其選擇正確的行,你是不是設置正確的指數。

如果你想讓它選擇倒數第二,即使字符串數/數組中的對象不同,只是將其設置爲

int row = [programTypes count]-2; //[programTypes count]-1 is the last row. 
+0

,但我想選擇的最後一行。所以,當我有9個元素的數組中,行= 8它應該選擇最後一行,對吧? - 但它總是選擇row = 8的第二行:-( – BennoDual

+0

你確定你的numberOfRowsInComponent返回了正確的數字,而titleForRow返回的是正確的標題嗎?不知道爲什麼它會出錯。 –

0

在您的代碼段變量programTypes.count收益爲計數9,並將selectedRow設置爲8,以便選擇器選擇最後一行。

+0

喜歡回答calvinBhai,我知道數組是從0開始指定的。所以,當我有9個元素時,當我使用索引8作爲行時,它應該選擇最後一行,但是它會選擇最後一行:-( – BennoDual