Question

So i've created a custom TableViewCell, and in the nib I put a UISwitch. Before I had even hooked it up to anything, if I ran it in the simulator and clicked on it, it would switch from off to on with the animation and such.

I'm trying to add a feature where the user is only allowed to change from off to on when a certain condition is true. I want it so, when the user touches the switch, it checks if the condition is true, and if it isn't it the switch doesn't move.

I've set up an IBAction where if the user Touches Up Inside, it'll run my function. My function is this:

if([on_switch isOn])
    {
        if([my_switch canSwitchOn])
        {
            NSLog(@"SWITCHED ON SUCCESSFULLY");
            [on_switch setOn:TRUE animated:TRUE];
        }
        else
        {
            NSLog(@"SWITCHED ON UNSUCCESSFULLY");
                        //Put in popup here
        }
    }
    else
    {
        [[ClassesSingleton sharedSingleton] classSwitchedOff:cell_index];
        [on_switch setOn:FALSE animated:TRUE];
    }

However, no matter what I do, that switch will flip, even though I gave it no directions to do so. I'm pretty sure it's the auto-flip that cause it to do so even before I'd hooked anything up to it. Is there a way to turn that off?

Thanks!

Was it helpful?

Solution

What you need to do is set userInteractionEnabled property to False on your UISwitch.

If you had allready made the connection in Interface Builder to an IBOutlet you delared in your owning class, you would be able to set it in code like this:

mySwitch.userInteractionEnabled = NO;

You could also set the property directly in Interface Builder by selecting the checkbox, as shown below (However in your app, you are going to need to wire the button up to an IBOutlet anyway to implement your conditional logic.) alt text http://www.clixtr.com/photo/ef06c1f7-8cca-40cd-a454-5ca534ceb9fe

OTHER TIPS

I think you will need something like the following:

// Somewhere just after the creation of _switch
[_switch addTarget:self action:@selector(switchValueDidChange:) forControlEvents:UIControlEventValueChanged];

// Target/Action method
- (void)switchValueDidChange:(UISwitch *)sender {
    if(sender.on && [self canSwitchOn] == NO){
        [sender setOn:NO animated:YES];
        // Popup
    }
}

Problem you're having is that the switch has already committed it's on state on touch up. When that's not the case (I'm not sure, never tested) you have to check whether the switch is currently not on. This bit of code will revert the state when the user was not allowed to switch the switch.

A better way is to disable the control, but maybe that's not what you want in this case.

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