2009-10-28 70 views
18

我有一個選擇器視圖,它有一個可供選擇的數字列表。我想能夠在特定行初始化控件。例如,如果用戶指定10作爲它們的默認值,那麼當控件第一次初始化時,控件應該自動定位在該行。iphone SDK:如何設置UIPickerView的初始值?

在此先感謝。

回答

55

您可以撥打selectRow:inComponent:animated:並將其傳遞給您想要選擇的行的索引。

此代碼將導致一個UIPickerView通過其數字旋轉0到60來對0

- (void)viewDidAppear:(BOOL)animated { 

    [thePicker selectRow:60 inComponent:0 animated:YES]; 
    [thePicker reloadComponent:0]; 
    [thePicker selectRow:60 inComponent:1 animated:YES]; 
    [thePicker reloadComponent:1]; 
    [thePicker selectRow:0 inComponent:0 animated:YES]; 
    [thePicker reloadComponent:0]; 
    [thePicker selectRow:0 inComponent:1 animated:YES]; 
    [thePicker reloadComponent:1]; 
} 

休息,你的情況,顯示連續十次,你會打電話像前:

[thePicker selectRow:10 inComponent:0 animated:YES]; 
+0

它不工作如預期。我把這個代碼放在controller的viewDidLoad中。不知道爲什麼? [tipPicker selectRow:5 inComponent:0 animated:YES]; – 2009-10-28 22:29:09

+0

解決IB問題後,解決方案正常工作。 – 2009-10-28 23:27:27

+0

不錯的演示。謝謝。 – 2009-10-29 21:41:35

0

你可以做什麼,而不是選擇行,是讓pickerview找到你想要的值。該方法是創建一個循環來找到它在數組中,並選擇它:

- (void)viewDidAppear:(BOOL)animated{  
    int i = 0; 
    for(NSString* number in arrayName) 
    { 
     if ([stringValue isEqualToString:number]){ 
      [pickerViewName selectRow:i inComponent:0 animated:YES ]; 
     } 
     i++; 
    } 
} 
0

如果使用UITextFieldUIPickerView

[self.text_field setInputView:self.picker]; 

然後使用此:

self.text_field.text = [_myarray objectAtIndex:10];