views:

2269

answers:

2

How can you dynamically add values to UIPickerView at runtime.

I'm using the following code to populate a UIPickerView statically. Need to add values dynamically at run time, for e.g. Three, Four etc.

- (NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    NSString *title = nil;
    if(row==0){
     title = @"One"; 
    }
    if(row==1){
     title = @"Two"; 
    }
+3  A: 

If you had an array of the titles, you could use something like:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
  return [titles objectAtIndex:row];
}

The titles will be refreshed when you call [pickerView reloadAllComponents] (or reloadComponent: if you have more than one column and only want to refresh one of them).

Ben Alpert
On what event would the UIPickerView re-read the values?
L. DPenha
Sorry, I should have mentioned that. Updated.
Ben Alpert
A: 

hey i had a problem with UIPickerView..... when i call reloadAllComponents it wasn't calling widthForComponent, but it was calling other delegate methods such as titleForRow.... i have no idea why this is, perhaps apple doesn't want the width changing dynamically? anyway it was on another screen so i didn't have the animation/no-animation issue. i found that by resetting the delegate of the picker, i could get widthForComponent to be called again!

i.e.

picker.delegate = view;

where view implements UIPickerViewDelegate.... hope this helps someone out there!

essetesse