Search code examples
iosuipickerviewuiswitch

Changing pickerview's value using a switch


I have a couple of picker views and a switch. What I would like to do is change the values of the pickers every time the button is toggled. For simplicity, let's say that I want to select the second row of each picker when the switch is on, and select the tenth row of each picker when the switch is off. From what i gathered in the past couple of hours, the way to do this is as follows:

// action called when the switch is toggled
- (void) switchToggled:(id)sender {

if ([sender isOn]) {
    [picker1 selectRow:2 inComponent:0 animated:YES]; 
    [picker2 selectRow:2 inComponent:0 animated:YES]; 
  }
else {
    [picker1 selectRow:10 inComponent:0 animated:YES];    
    [picker2 selectRow:10 inComponent:0 animated:YES];    
  }
}

This doesn't seem to working, though. I also noticed that the selectRow:inComponent method doesn't change the value of the picker unless it is called when the view is being drawn/redrawn, or when it's being called from the didSelectRow:inComponent method.

Any ideas?


Solution

  • SelectRow: inComponent: animated: has always worked to move the picker for me, and I've done stuff like this plenty. The thing that used to catch me out is that will trigger pickerview: didSelectRow: inComponent: on the delegate, which I generally only want called when the setting has come from the user, not from my own code. The way to work around this is either

    picker.delegate = nil;
    [picker selectRow:foo inComponent:bar animated:probably];
    picker.delegate = thatObjectWhichWasDelegateAsecondAgo;
    

    Or have a bool ivar you cans set to no briefly eg listenToPicker, then inside didselectrow..

    -(void)pickerview:pickerview didSelectRow:row inComponent:component{
    
    if (listenToPicker){
    
    ///act on input
    
    
    }}