Friday, August 20, 2010

Create UIPickerView programmatically

The UIPickerView is one of the input controls in iOS for displaying and selecting a list of data. Most tutorials implement this control in Interface Builder, which is fine, but I like to have more control and do most everything in code. There are several components to doing this 100% programmatically, which I will demonstrate below...

The first thing we have to do is include the UIPickerViewDelegate in the interface of our class .h file.
@interface myViewController : UIViewController<UIPickerViewDelegate>

Next, actually create the UIPickerView by setting the frame, setting the delegate, making the selection highlight visible and adding it to the main view.
UIPickerView *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 320, 200)];
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
[self.view addSubview:myPickerView];

Finally, we have to implement the delegate methods to control the look and functionality.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component {
    // Handle the selection
}

// tell the picker how many rows are available for a given component
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    NSUInteger numRows = 5;

    return numRows;
}

// tell the picker how many components it will have
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
 return 1;
}

// tell the picker the title for a given component
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString *title;
    title = [@"" stringByAppendingFormat:@"%d",row];

    return title;
}

// tell the picker the width of each row for a given component
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
 int sectionWidth = 300;

 return sectionWidth;
}

8 comments:

  1. Great tutorial!
    I'd like to say that if you create the UIPickerView that way you have to release it after adding it as subview:

    UIPickerView *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 320, 200)];
    ...
    [self.view addSubview:myPickerView];

    [myPickerView release];

    ReplyDelete
  2. I would suggesting adding a screen shot of the window to your post(s). Just makes things more visually appealing.

    ReplyDelete
  3. What if you want the picker view to go away when its done?

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Just curious is there a way to set the rows differently if there are more then one component? same for width?

    ReplyDelete