【问题标题】:NSRangeException when trying to set default UIPickerView value尝试设置默认 UIPickerView 值时出现 NSRangeException
【发布时间】:2011-07-15 15:15:56
【问题描述】:

我在弹出窗口中有一个 UIPickerView。我只是想在显示弹出框之前设置选择器视图的默认/起始值。这是我用来创建和显示弹出框的代码(在处理触摸按钮操作的方法中):

- (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 设置默认/起始值?

我确定这里有一个简单的解决方案,但我只是没有看到它......

谢谢

【问题讨论】:

    标签: objective-c ipad exception uipickerview popover


    【解决方案1】:

    检查组件的数量是否有效且currentStep.length - 1不大于8

    您的主要问题是您没有设置选择器的dataSource。添加

    timePicker.dataSource = self;
    

    【讨论】:

    • 我已将其设置为 1 个组件。 currentStep.length - 1 等于 2。我将类设置为实现 UIPickerViewDataSource 并设置 timePicker.dataSource = self;,但我仍然得到相同的异常。你确定这不是一个未初始化的东西吗?似乎有道理,加上错误消息的详细信息显示index 1 beyond bounds [0 .. 0],这将导致该结论。还有其他建议吗?
    • 刚刚发现问题。组件是 0 索引的。我将其更改为[timePicker selectRow:(currentStep.length - 1) inComponent:0 animated:YES];,它运行良好。
    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多