2011-05-28 16 views
16

estoy tratando de detectar cuando un UISwitch desconexión/¿Cómo detectar si UISwitch está encendido/apagado?

// .h 
IBOutlet UISwitch *privateSwitch; 
@property (nonatomic, retain) IBOutlet UISwitch *privateSwitch; 

//.m 
@synthesize privateSwitch; 
privateSwitch = [[UISwitch alloc] init]; 
howToDisplay = @"no"; 

// In my cellForRowsAtIndexPath 
UISwitch *privateSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(199, 8, 0, 0)]; 
[privateSwitch addTarget:self action:@selector(switchToggled:) forControlEvents: UIControlEventTouchUpInside]; 
[cell.contentView addSubview:privateSwitch]; 

if ([howToDisplay isEqualToString:@"no"]) { 
    [privateSwitch setOn:NO animated:NO]; 
} else { 
    [privateSwitch setOn:YES animated:NO]; 
} 

- (void) switchToggled:(id)sender { 

if ([privateSwitch isOn]) { 
NSLog(@"its on!"); 
howToDisplay = @"yes"; 
[formDataTwo removeAllObjects]; 
[formTableView reloadData]; 
[privateSwitch setOn:YES animated:YES]; 
} else { 
NSLog(@"its off!"); 
howToDisplay = @"no"; 
[formDataTwo removeAllObjects]; 
[formDataTwo addObject:@"Facebook"]; 
[formDataTwo addObject:@"Twitter"]; 
[formDataTwo addObject:@"Flickr"]; 
[formDataTwo addObject:@"Tumblr"]; 
[formDataTwo addObject:@"Email"]; 
[formDataTwo addObject:@"MMS"]; 

[formTableView reloadData]; 
[privateSwitch setOn:NO animated:YES]; 
} 

}

Sin embargo, cuando lo enciendo, se dirá que es apagado. ¿Lo que da?

Gracias.

Respuesta

52

En su método cellForRowsAtIndexPath está declarando una variable local UISwitch *privateSwitch que está ocultando su variable de instancia privateSwitch.

En su acción switchToggled:, está utilizando su variable de instancia para probar el estado del conmutador, no el declarado en cellForRowAtIndexPath. Puede utilizar el parámetro sender así:

- (void) switchToggled:(id)sender { 
    UISwitch *mySwitch = (UISwitch *)sender; 
    if ([mySwitch isOn]) { 
     NSLog(@"its on!"); 
    } else { 
     NSLog(@"its off!"); 
    } 
} 

P.S: Me gustaría utilizar en lugar de UIControlEventValueChangedUIControlEventTouchUpInside.

+0

Gracias. ¡Estúpido error! Se eliminó 'UISwitch *' y funcionó como un amuleto. – iosfreak

+0

De nada :) – albertamg

Cuestiones relacionadas