Try the search, it's linked to some great forums

Friday, June 15, 2012

UIPickerView snippet



The UIPickerView is a simple & pretty UI element for selecting items.  It mimics the wheels on a slot machine.  Below is the snippets that allow for the configuring of the displayed view.  Each wheel is a component, and the data items in each wheel are defined as a row element.

                          
define the pickerView and an array for the data to be displayed
in FlipsideViewController.h -
@property (strong, nonatomic) IBOutlet UIPickerView *heightPicker;
@property (strong, nonatomic) NSArray *pickerItems;

implement the required delegate and dataSource methods. 
in FlipsideViewController.m -
#pragma mark ---- UIPickerViewDataSource delegate methods ----

// returns the number of columns to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

// returns the number of rows
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self.pickerItems count];
}

#pragma mark ---- UIPickerViewDelegate delegate methods ----

// returns the title of each row
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [self.pickerItems objectAtIndex:row];
}

// gets called when the user settles on a row
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
// Picks out the component & it's value 
    NSString *componentValue = [self.pickerItems objectAtIndex:row];
   
// assigns row values to feet or inches & calculates the fractional feet
    if (component == 0) {
        feetComponent = [componentValue floatValue];
    }
    if (component == 1) {
        inchesComponent = [componentValue floatValue];
    }
// calculates fractional feet value   
    flagHeight = feetComponent + (inchesComponent / 12);
    self.flipsideInfo.text = [NSString stringWithFormat:@"= %2.2f feet", flagHeight];    
}
Oh, and don't forget to synthesize the NSArray & UIPickerView instance variables.