Trying to turn one UISwitch on from group, and disabling others simultaneously in iOS

StackOverflow https://stackoverflow.com/questions/21297167

  •  01-10-2022
  •  | 
  •  

Question

I am working on an application where I have a UISwitch(switch1) that controls other UISwitches(switches 2-5). If switch1 is on, switches 2-5 are off, and disabled. If switch1 is off, switches2-5 should be off but enabled, allowing the user to turn one of these other switches on or off.

Now, if a switch from 2-5 are on, then all the others from 2-5 should be off, and disabled. It is only when the switch that is on from 2-5 is off again, are all switches from 2-5 enabled. In other words, switches 2-5 are all enabled, only when they are all off, and are all disabled, when one of them is on. I am trying to do this with my code but not successful as of yet. Here is what I have:

- (IBAction)MainSwitchAction:(id)sender {

    if (self.mySwitch.on) {

        [self disableCheckBoxes:YES];

    }  else if (!self.mySwitch.on){

        [self disableCheckBoxes:NO];
    }

}  

The above method is called when the primary switch is turned on/off. My other method is:

-(void) disableCheckBoxes:(BOOL)switchOff {

    if (switchOff==YES) {

        for (int i = 1; 2 < 6; i++) {

            UISwitch *sw = (UISwitch *)[self.view viewWithTag:i];
            sw.on = NO;
            sw.enabled = NO;

        }


    }  else if (switchOff==NO){

        for (int i = 2; i < 6; i++) {

            UISwitch *sw = (UISwitch *)[self.view viewWithTag:i];
            sw.on = NO;
            sw.enabled = YES;

        }

    }

}

My problem is the following:

At startup, my default value for the switch1 is ON, which means all the other switches should be off, and disabled. However, switch2 for some reason is enabled. When I turn switch1 off, switches 3-5 are enabled. Finally, when I move a switch from 2-5 on, the other remaining switches are disabled (correctly), however, when I turn the very switch that was on, to off, none of the switches from 2-5 are enabled. Why?

Can anyone see what it is I'm doing wrong?

Was it helpful?

Solution

Add tags to the UISwitch in storyboard, then after you include the UISwitches to a collection as mentioned above, you can do something like:

- (IBAction)switchCollectionTapped:(UISwitch *)sender {

    [self.switchCollection enumerateObjectsUsingBlock:^(UISwitch *obj, NSUInteger idx, BOOL * _Nonnull stop) {

        if (sender.tag != obj.tag) {
            [obj setOn:NO];
        }
    }];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top