Turn a switch Off or On on the basis of another switch state

3.3k views Asked by At

How can I turn a switch off inside a different switch? Here's an example - When the isMale switch is turned on, turn off the isFemale switch.

- (IBAction)isMale:(id)sender {
       if ([sender isOn]) {

             //TURN isFemale SWITCH OFF

       }
       else {
            ...
       }
 }

and

- (IBAction)isFemale:(id)sender {
       if ([sender isOn]) {

            //TURN isMale SWITCH OFF

       }
       else {
            ...
       }
 }

I've been reading the Apple development docs but cannot find anything about changing a switch inside another switch. Cheers.

4

There are 4 answers

0
Syed Ali Salman On BEST ANSWER

first of all you need to create IBOutlet of both UISwitch in your header .h file

@property (strong, nonatomic) IBOutlet UISwitch *isMale;
@property (strong, nonatomic) IBOutlet UISwitch *isFemale;

then in your IBAction do as follow.

- (IBAction)isMale:(id)sender {
   if ([sender isOn]) {

         [_isFemale setOn:NO animated:YES];

   }
   else {
        // do what you want.
   }
}
- (IBAction)isFemale:(id)sender {
   if ([sender isOn]) {

        [_isMale setOn:NO animated:YES];

   }
   else {
        //do what you want
   }
}

remember to connect both of your IBOutlet to respective objects in your UIViewController.

0
user4261201 On

Here is simple example which you need

- (void)viewDidLoad 
 {
    [super viewDidLoad];
   // Do any additional setup after loading the view, typically from a nib.

    [_btnMale setOn:YES animated:YES];
    [_btnFemale setOn:NO animated:YES];

 }


 - (IBAction)btnMaleClick:(id)sender
 {
     if ([sender isOn])
     {
        [_btnFemale setOn:NO animated:YES];
     }

 }

 - (IBAction)btnFemaleClick:(id)sender
 {
    if ([sender isOn])
    {
       [_btnMale setOn:NO animated:YES];
    }

  }
0
adrienMarsden.jpeg On

here is how to switch button state in swift for future reference

override func viewDidLoad() {
    super.viewDidLoad()

    btnMale.setOn(true, animated: true)
    btnFemale.setOn(false, animated: true)

}

@IBAction func btnMaleClick(sender: UISwitch){
    if sender.on{
        btnFemale.setOn(false, animated: true)
    }
}
@IBAction func btnFemaleClick(sender: UISwitch){
    if sender.on{
        btnMale.setOn(false, animated: true)
    }
}
0
jbiser361 On

in swift 5.1 (Xcode 11) use

       [switchPass .setOn(false, animated: true)]