Question

I've got a UISwitch in a UIPopoverController and it's default setting is ON when you open up the popover VC. I'm trying to have it so that when you set it to "OFF" and you close the UIPopover - when you reopen the popover, the state of the UISwitch remains the same. For the life of me I can't figure this out and I bet it's something really simple. I was wondering if anyone might be able to point me in the right direction? Any help would be really appreciated thanks!

[EDIT] This is the code I'm working with:

  //--NEW CODE--//
#define SWITCH_KEY_STATE @"Save UISwitch State"

- (IBAction)settingsPopover:(id)sender {
    if(![pop isPopoverVisible]){
        settings = [[settingsView alloc] initWithNibName:@"settingsView" bundle:nil];
        settings.setDelegate = self;
        pop = [[UIPopoverController alloc] initWithContentViewController:settings];
        [pop setPopoverContentSize:CGSizeMake(200, 100)];
        [pop presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        //--NEW CODE--//
        popoverState = [NSUserDefaults standardUserDefaults];
        self.settings.hintSwitch.on = [popoverState boolForKey:SWITCH_KEY_STATE];

        [self.settings.hintSwitch addTarget:self action:@selector(onOff:) forControlEvents:UIControlEventValueChanged];
    } else {
        [pop dismissPopoverAnimated:YES];
    }
}

This is the function to create the popover the [self.settings.hintSwitch... is the popover (settings) calling on the UISwitch which when it's interacted with it runs this void function:

- (void)onOff:(id)sender {
    if (settings.hintSwitch.on) {
        tutView.hidden = NO;
    } else {
        tutView.hidden = YES;
    //--NEW CODE--//
    popoverState = [NSUserDefaults standardUserDefaults];
    [popoverState setBool:self.settings.hintSwitch.on forKey:SWITCH_KEY_STATE];
        }
    }

So that works find it's just when I close the popover and re open it, it resets the UISwitch to "ON".

[EDIT2] I've edited the code above to what I've added in. Which Works!

Was it helpful?

Solution

the first thing I see is this line of code:

pop = [[UIPopoverController alloc] initWithContentViewController:settings];

With it you re-alloc every time you controller, initializing it with initial setup (ON on default).

You have this solution:

  1. create a BOOL in your class called like "popoverState"
  2. save the state of your UISwitch before dismissing your popovercontroller
  3. once you init it, you can use the new variable to set the state of the switch

Let me now!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top