Search code examples
uipickerview

Custom Picker View for iOS 6.1


I am trying to setup a simple custom picker view that has two components based on arrays. The first array (used in component 0) is defined as:

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

The second array (used in component 1) is defined as:

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"];

The I am using the following code to create the custom view:

 - (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;

}

The UI of the picker works great and first component loads correctly, the issue is that for the second component I get:

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

It's not loading the full "tenthsScore" array properly. I'm at a complete loss.

Any ideas?


Solution

  • In the future, please make an effort to format your code properly. Doing so makes it easier for us to help you.

    Anyway, you're only setting the label's text when you're first creating the label. In the case when you're reusing a label, you just return the reused label unchanged.

    - (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;
    }