UIPicker selectRow not working - what is wrong with this code?

I am trying to set the default value for a UIPickerView. However, no matter what value I set it to, it always defaults to 1. The method below loads the collector just fine, and I can select it. So what am I doing wrong? Here is the code.

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. arrayNo = [[NSMutableArray alloc] init]; [arrayNo addObject:@" 1 "]; [arrayNo addObject:@" 2 "]; [arrayNo addObject:@" 3 "]; [arrayNo addObject:@" 4 "]; [arrayNo addObject:@" 5 "]; [pickerView selectRow:4 inComponent:0 animated:YES]; mlabel.text= [arrayNo objectAtIndex:[pickerView selectedRowInComponent:0]]; } 

Picker DataSource Methods:

 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { mlabel.text = [arrayNo objectAtIndex:row]; NSNumberFormatter * f = [[NSNumberFormatter alloc] init]; [f setNumberStyle:NSNumberFormatterDecimalStyle]; NSNumber * myNumber = [f numberFromString:[arrayNo objectAtIndex:row]]; [f release]; prefs = [NSUserDefaults standardUserDefaults]; NSInteger myInteger = [myNumber integerValue]; // save level [prefs setInteger:myInteger forKey:@"myInt"]; // saving it all [prefs synchronize]; } - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component; { return [arrayNo count]; } 
+7
source share
7 answers

It works if I put it in this method:

 -(void) viewWillAppear: (BOOL) animated 
+7
source

You may need to call reloadAllComponents after filling the array and before trying to select a row. The collector may not know your new number of items.

+5
source

Take the following steps

  • load an array before initializing the collector.
  • call [pickerView selectRow: 4 inComponent: 0 animated: YES];
  • call [pickerView reloadAllComponents];

The latest Apple release notes in apples say: "In iOS 5.0, UIPickerView does not send its pickerView: didSelectRow: inComponent: delegate message due to programmatic choice." Therefore, we need to force relaodAppComponents ..

Recognize if his job ...

+2
source

This is due to the fact that you need to set the data source in viewdidload otherwise, if you install it from the storyboard, it will be loaded after viewing WillAppear.

+1
source
  • we cannot see how you configure the data source for the collector
  • you make an animated selectRow in viewDidLoad (this view is not yet on the screen ...)

Have you tried with animated: NO?

0
source

What does arrayNo do? Is it used to populate a UIPickerView? If so, you need [pickerView reloadAllComponents] before calling selectRow:inComponent:animated:

0
source

What worked for me was delegating the didSelectRow call:

 self.pickerView.delegate?.pickerView?(self.providerPickerView, didSelectRow: 0, inComponent: 0) 
0
source

All Articles