我有一个带有2个组件的UIPickerView。
这是加载到其中的数组:
pickerArray = [[NSMutableArray alloc] initWithCapacity:700];
for ( int i = 0 ; i <= 1000 ; ++i)
[pickerArray addObject:[NSString stringWithFormat:@"%d", i]];
pickerArrayHalf = [[NSMutableArray alloc]initWithCapacity:2];
[pickerArrayHalf addObject:@".0 lb"];
[pickerArrayHalf addObject:@"1/2 lb"];
以下是委托方法:
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView
{
if (thePickerView.tag==1)
{
return 2;
}
else
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component
{
if (thePickerView.tag==1)
{
if (component == 0)
return [pickerArray count];
if (component == 1)
return [pickerArrayHalf count];
}
else
return [pickerArray count];
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (thePickerView.tag==1)
{
NSLog(@"Selected weight 1: %@. Index of array: %i", [pickerArray objectAtIndex:row], row);
NSLog(@"Selected weight 2: %@. Index of array: %i", [pickerArrayHalf objectAtIndex:row], row);
}
else
{
NSLog(@"Selected rep number: %@. Index of array: %i", [pickerArray objectAtIndex:row], row);
}
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
if (pickerView.tag==1)
{
if (component == 0)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)];
int weight = [[pickerArray objectAtIndex:row] intValue];
label.text = [NSString stringWithFormat:@"%d", weight];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:30];
[label autorelease];
return label;
}
else
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 37)];
label.text = [pickerArrayHalf objectAtIndex:row];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:30];
[label autorelease];
return label;
}
}
滚动时,应用程序在第NSLog(@"Selected weight 2: %@. Index of array: %i", [pickerArrayHalf objectAtIndex:row], row);
任何想法为什么?
答案 0 :(得分:0)
您的选择器视图有两个组件/列。您必须分别处理每个组件的滚动。在您的情况下,即使该方法特定于组件,您也会在两个组件的行索引处打印出值。
因此,如果我要滚动到第一列中的第十行,您将尝试打印两个数据源的第十个元素。鉴于第二列的数据源似乎只有2个元素,只要第一列滚动超过前两个值,您的应用程序就会崩溃。
您需要像在numberOfRowsInComponent:方法中那样基于给定的组件实现逻辑。