Search code examples
iosuiswitch

How to set switch on/off state iOS?


I tried to set a switch to on state using [self.switchAutoPlay setOn:YES]. But It's not working. Here what I've done,

In interface

@property (weak, nonatomic) IBOutlet UISwitch *switchAutoPlay;

In implementation

[[self switchAutoPlay] setOn:YES];

Let me know a way to make this work.


Solution

  • initially check , Did you connect your outlet of UISwitch

    in your viewdidload

     switchAutoPlay.isOn --> is for on 
    
    !switchAutoPlay.isOn --> is for off
    

    for method

    [switchAutoPlay addTarget: self action: @selector(flip:) forControlEvents: UIControlEventValueChanged];
    

    for method of

     - (IBAction)flip:(id)sender{
    
    if([sender isOn]){
        NSLog(@"Switch is ON");
    } else{
        NSLog(@"Switch is OFF");
    }
    
    }
    

    Choice-2

    UISwitch, seen in the developper API, the task setOn: animated: should do the trick.

    - (void)setOn:(BOOL)on animated:(BOOL)animated
    

    So to set the switch ON in your program, you would use:

    Objective-C

    [switchAutoPlay setOn:YES animated:YES];