Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect whether UISwitch is on/off?

I am trying to detect when a UISwitch it on / off

// .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];
}

}

However, when I switch it on, it will say it's off. What gives?

Thanks.

like image 593
iosfreak Avatar asked May 28 '11 17:05

iosfreak


1 Answers

In your cellForRowsAtIndexPathmethod you are declaring a local variable UISwitch *privateSwitch that is hiding your instance variable privateSwitch.

In your switchToggled: action, you are using your instance variable to test the state of the switch, not the one declared in cellForRowAtIndexPath. You can use the sender parameter like this:

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

P.S: I would use UIControlEventValueChanged instead of UIControlEventTouchUpInside.

like image 106
albertamg Avatar answered Oct 21 '22 07:10

albertamg