Cocoa-Matic

iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

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

Labels: , ,

8 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home


« Older Entries  
Newer Entries »