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; }
Thank you!
ReplyDeleteGreat tutorial!
ReplyDeleteI'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];
I would suggesting adding a screen shot of the window to your post(s). Just makes things more visually appealing.
ReplyDeleteWhat if you want the picker view to go away when its done?
ReplyDeletenice
ReplyDeleteThank you!
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteJust curious is there a way to set the rows differently if there are more then one component? same for width?
ReplyDelete