16

I have the following code to create a UIPickerView:

pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0f, 416.0f - height, 320.0f, height)];
pickerView.delegate = self;
pickerView.showsSelectionIndicator = YES;
[pickerView setSoundsEnabled:YES];

I would like to change the component widths and change the text size in each component. Is it possible to do this?

Thanks!

Chris Hanson's user avatar

Chris Hanson

55.4k8 gold badges75 silver badges104 bronze badges

asked Nov 2, 2008 at 5:26

rksprst's user avatar

51

You can change the width by an appropriate delegate method

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    switch(component) {
        case 0: return 22;
        case 1: return 44;
        case 2: return 88;
        default: return 22;
    }

    //NOT REACHED
    return 22;
}

As for a custom text size, you can use the delegate to return custom views with whatever sized text you want:

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

        retval.text = @"Demo";
        retval.font = [UIFont systemFontOfSize:22];
        return retval;
}

Of course you will need modify these to have appropriate values for your app, but it should get you where you need to go.

Max MacLeod's user avatar

Max MacLeod

26.8k14 gold badges110 silver badges137 bronze badges

answered Nov 2, 2008 at 6:24

Louis Gerbarg's user avatar

3 Comments

A couple of errors in your second code block: - The UIView needs to be cast to (UILabel*). - The retval assignment line is missing an opening bracket and needs to call initWithFrame otherwise we'll get nothing displayed: ie. retval = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)] autorelease];

Thanks, I'll make appropriate changes, though not exactly what you propose. I am going to cast through an id, basically because it is shorter and you don't give anything up because the lval of the expression is already typed to a UIView.

I also want to add this line to the answer in case you are working with an array to populate the picker (most likely). Instead of retval.text = @"Demo", replace with retval.text = [messageArray objectAtIndex:row];

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.