Sunday, March 20, 2011

Creating UIPickerView

The following steps outline how to create a UIPickerView in an iPhone application.
1. Create the UIPickerView in Interface Builder.
2. Add the IBOutlet for the UIPickerView in the interface file (.h) for the view. Add the @synthesis for the IBOutlet in the objective c code (.m) for the view. (Optional, if the UIPickerView is needed to reference in the code)
eg. in the interface (.h) file
@interface controller : UIViewController {
       IBOutlet UIPickerView *picker;
}
@property (nonatomic, retain) IBOutlet UIPickerView *picker;

eg. in the implementation code (.m) file
@synthesize picker;
3. Link the picker IBOutlet to the UIPickerView in Interface Builder. (optional only if step 2 is followed)
4. The following 1 delegate and 3 datasource methods need to be implemented:
a. numberOfComponentsInPickerView, this datasource method should return the number of components in the UIPickerView. (Optional, only needed for multiple components UIPickerView)
   eg:
   - (NSInteger) numberOfComponentsInPickerView: (UIPickerView *)thePickerView {
         return numberOfComponentsInPickerView;  // this should return the number of components in the UIPickerView
   }
b. numberOfRowsInComponent, this datasource method should return the number of rows in the component.
    eg:
    -(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent: (NSInteger) component {
          return [componentArray count];
    }
c. titleForRow, this datasource method should return the title of the row in the picker view
    eg:
    -(NString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent: (NSInteger) component {
          return [componentArray objectAtIndex:row];
    }

d. didSelectRow, this delegated method will be invoked when user select the item in the picker view.
    (Optional, only needed if some action is needed to perform when user select the item on the UIPickerView)
* When there are multiple components in the picker, this method is only called once, when two components are turned together.
    eg:
    -(void)pickerView:(UIPickerView *)thePickerView didSelectRow: (NSInteger)row inComponent: (NSInteger) component  {
          selectedIndex = row;
     }

5. Link the datasource and delegate for the UIPickerView to the delegate implementation in the Interface Builder.

No comments:

Post a Comment