Search code examples
iosobjective-cuipickerview

Setting unique default values for multiple UIPickerViews in the same View Controller Objective C


I have a View Controller with two distinct UIPickerViews. The first is a contains seven names. The second is a list of numbers(strings) from 1 to 100. I want the default to be the last number in the list.

I have set the first UIPickerView's default value using the following method which I call in viewDidLoad.

[self.namePicker selectRow:2 inComponent:0 animated:YES];

This works just fine and my namePicker shows the third element when I run the code.

However, the following method call does not work for my second UIPickerView(also being called in viewDidLoad).

[self.numberPicker selectRow:99 inComponent:0 animated:YES];

There are no errors when I run, the numberPicker just appears with a default value of 1 (the first element) every time.


Solution

  • The issue could be that your UIPickerView dataSource and delegate methods are not differentiating between the two UIPickerViews. One way to handle that would be to give them separate tags in InterfaceBuilder and then use if and/or switch statements in your delegate and datasource methods:

    #define kNamesPicker            0     // tag assigned in IB
    #define kNumberPicker           1     // tag assigned in IB
    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    if (pickerView.tag == kNamesPicker) {
    }
    else if (pickerView.tag == kNumberPicker) {
    }
    

    Once your delegate and datasource methods are sorted assigning values to the pickers should work fine.