Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UISwitch Action called twice

Tags:

ios

uiswitch

I have UISwitch IBAction in my app, which is:

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

        if(nearMeSwitch.isOn)
            [self getLocation];

        [self myMethod];
}

- (void) getLocation
{
  my code...
 [nearMeSwitch setOn:NO animated:YES];
}

In my getLocation method I've used [nearMeSwitch setOn:NO animated:YES] which calls nearMeSwitchAction again when I click on my switch. Therefore myMethod gets called twice. I dont want that. I don't want to execute nearMeSwitchAction when I turn off my switch from getLocation. Is there other way to accomplish this?

like image 470
NotABot Avatar asked Feb 05 '26 05:02

NotABot


1 Answers

You cannot stop nearMeSwitchAction to get called when you changed UISwitch value, but you can stop your myMethod to getting called. Create one Bool property like isFromGetLocation and if it is true don't call the method.

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

        if(nearMeSwitch.isOn)
            [self getLocation];
        if(isFromGetLocation)
           //For next time
           isFromGetLocation = NO;
        else
            [self myMethod];
}

- (void) getLocation
{
    //my code...
    isFromGetLocation = YES;
    [nearMeSwitch setOn:NO animated:YES];
} 
like image 125
Nirav D Avatar answered Feb 07 '26 20:02

Nirav D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!