Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIPicker selectRow not working - what's wrong with this code?

I'm trying to set a default value for the UIPickerView. However, no matter which value I set it to, it always defaults to 1. The method below loads the picker just fine, and I can select it. So, what am I doing wrong? Here's 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's 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];
}
like image 673
Jack BeNimble Avatar asked Sep 12 '11 20:09

Jack BeNimble


1 Answers

What worked for me is to delegate the didSelectRow call:

self.pickerView.delegate?.pickerView?(self.providerPickerView, didSelectRow: 0, inComponent: 0)
like image 73
TalMihr Avatar answered Oct 18 '22 03:10

TalMihr