2011-07-15 44 views
1

我在彈出窗口中有一個UIPickerView。我只是試圖在彈出窗口顯示前設置選擇器視圖的默認/起始值。下面是我用來創建和顯示酥料餅(在該方法中處理觸摸了按鍵動作)的代碼:當試圖設置默認UIPickerView值時出現NSRangeException

- (IBAction) handleClickStepTimeButton: (id)sender 
{ 
    UIViewController *timePickerController = [UIViewController alloc]; 

    UIPickerView *timePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 100, 180)]; 
    timePicker.delegate = self; 
    timePicker.showsSelectionIndicator = YES; 
    [timePickerController.view addSubview:timePicker]; 

    UIPopoverController *timePickerPopoverController = [[UIPopoverController alloc] initWithContentViewController:timePickerController]; 
    timePickerPopoverController.popoverContentSize = CGSizeMake(100, 200); 

    UIButton *stepTimeButton = (UIButton *)sender; 

    [timePickerPopoverController presentPopoverFromRect:CGRectMake(stepTimeButton.frame.size.width, (stepTimeButton.frame.size.height/2), 1, 1) inView:stepTimeButton permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; 

    [timePicker selectRow:(currentStep.length - 1) inComponent:1 animated:YES]; 
} 

我沒有任何顧慮創建酥料餅和UIPickerView每單擊此按鈕,因爲它贏得了時間經常發生,因爲UIPickerView的值只是一小部分整數。下面是我使用的值添​​加到視圖代碼:

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { 
    return 8; 
} 
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)rowId forComponent:(NSInteger)component { 
    return [NSString stringWithFormat:@"%d", (rowId + 1)]; 
} 

我的問題是,我每次去展現酥料餅的時候,我就[timePicker selectRow...線得到NSRangeException。這種對我來說很有意義,因爲UIPickerView還沒有顯示出來。但是使用這種邏輯......如何爲UIPickerView設置默認/起始值?

我敢肯定,這裏有一個簡單的解決方案,但我只是沒有看到它......

感謝

回答

2

檢查是否組件的數量是有效的和currentStep.length - 1不大於8更大。

您的主要問題是您沒有設置選取器的dataSource。 Add

timePicker.dataSource = self; 
+0

我已經將它設置爲1個組件。 'currentStep.length - 1'等於2.我設置類來實現'UIPickerViewDataSource'並設置'timePicker.dataSource = self;',但我仍然得到相同的異常。你確定它不是非初始化的東西嗎?似乎是有道理的,再加上錯誤消息的詳細信息'index 1 beyond bound [0 .. 0]',這將導致這個結論。還有其他建議嗎? – user700774

+1

剛發現問題。組件是0索引的。我把它改成了'[timePicker selectRow:(currentStep.length - 1)inComponent:0 animated:YES];'它很高興地工作。 – user700774