How to tell when a UISwitch inside of a UITableViewCell has been tapped?

RexOnRoids picture RexOnRoids · Mar 27, 2010 · Viewed 8.6k times · Source

How to tell when a UISwitch inside of a UITableViewCell has been tapped?

My UISwitch is set up inside of the cell (generic cell) like this:

UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
[cell addSubview:mySwitch];
cell.accessoryView = mySwitch;

And I am trying to detect a tap like this (but its not working):

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {

    NSUserDefaults *prefs;


    if(indexPath.section == 1){

        switch(indexPath.row)
        {
            case 0:

                NSLog(@"Tapped Login Switch");              

                break;
            default:
                break;
        }

    }


}

Dave DeLong suggested that I set an action for each switch as a solution. So I did the following to set the switch:

        UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
        [mySwitch addTarget:self action:@selector(switchToggled2:) forControlEvents: UIControlEventTouchUpInside];
        if(at_songs){

            [mySwitch setOn:YES animated:NO];

        }
        [cell addSubview:mySwitch];
        cell.accessoryView = mySwitch;



And the following to know when it was tapped:

-(IBAction)switchToggled1:(id)sender {


    NSUserDefaults *prefs;

    NSLog(@"Tapped Login Switch");

    prefs = [NSUserDefaults standardUserDefaults];

    if(at_login){
        [prefs setObject:@"NO" forKey:@"autotweet_login"];
        at_login = NO;
    }else{
        [prefs setObject:@"YES" forKey:@"autotweet_login"]; 
        at_login = YES;
    }



}

Turning the switch ON is not a problem. The problem NOW is that when the UISwitch is set to OFF, for some reason its action gets called twice (And I get 2 NSLogs for 1 tap).



Why is the action getting called TWICE for only one tap to turn the switch OFF? How do I fix it?

Answer

Dave DeLong picture Dave DeLong · Mar 27, 2010

Give the switch a target and action:

[mySwitch addTarget:self action:@selector(switchToggled:) forControlEvents: UIControlEventTouchUpInside];

Then implement your switchToggled: method:

- (void) switchToggled:(id)sender {
  //a switch was toggled.  
  //maybe use it's tag property to figure out which one
}