适用于iOS 6.1的自定义选择器视图

时间:2013-08-07 16:42:16

标签: uipickerview

我正在尝试设置一个简单的自定义选择器视图,它包含两个基于数组的组件。第一个数组(在组件0中使用)定义为:

onesScore = [[NSMutableArray alloc]init];
[onesScore addObject:@"5"];
[onesScore addObject:@"6"];
[onesScore addObject:@"7"];
[onesScore addObject:@"8"];
[onesScore addObject:@"9"];

第二个数组(在组件1中使用)定义为:

tenthsScore = [[NSMutableArray alloc]init];
[tenthsScore addObject:@"0"];
[tenthsScore addObject:@"1"];
[tenthsScore addObject:@"2"];
[tenthsScore addObject:@"3"];
[tenthsScore addObject:@"4"];
[tenthsScore addObject:@"5"];
[tenthsScore addObject:@"6"];
[tenthsScore addObject:@"7"];
[tenthsScore addObject:@"8"];
[tenthsScore addObject:@"9"];

我正在使用以下代码创建自定义视图:

 - (UIView *)pickerView:(UIPickerView *)picker viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
UILabel* retval = (id)view;
if (!retval){
    retval= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [picker rowSizeForComponent:component].width, [picker rowSizeForComponent:component].height)];

    if (component == 0)
    {
        retval.text = [onesScore objectAtIndex:row];
    }
    else if (component == 1)
    {
        retval.text = [tenthsScore objectAtIndex:row];
    }

retval.font = [UIFont fontWithName:@"Helvetica" size:48];
retval.backgroundColor =[UIColor clearColor];
retval.textAlignment = NSTextAlignmentCenter;
}
return retval;

}

选择器的UI运行良好,第一个组件正确加载,问题是我得到的第二个组件:

0,1,2,3,4,5,0,1,2,3

它没有正确加载完整的“tenthsScore”数组。我完全失去了。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

将来,请努力正确格式化您的代码。这样做可以让我们更轻松地为您提供帮助。

无论如何,您只是在第一次创建标签时设置标签text。如果您重复使用标签,则只需更改重复使用的标签。

- (UIView *)pickerView:(UIPickerView *)picker viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel* retval = (id)view;
    if (!retval){
        retval= [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [picker rowSizeForComponent:component].width, [picker rowSizeForComponent:component].height)];
        retval.font = [UIFont fontWithName:@"Helvetica" size:48];
        retval.backgroundColor =[UIColor clearColor];
        retval.textAlignment = NSTextAlignmentCenter;
    }

    if (component == 0) {
        retval.text = [onesScore objectAtIndex:row];
    } else if (component == 1) {
        retval.text = [tenthsScore objectAtIndex:row];
    }

    return retval;
}