如何检测UISwitch是否打开/关闭?

时间:2011-05-28 17:48:22

标签: objective-c uiswitch

我正试图检测UIS开关何时打开/关闭

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

}

然而,当我打开它时,它会说它已关闭。是什么给了什么?

感谢。

1 个答案:

答案 0 :(得分:53)

cellForRowsAtIndexPath方法中,您声明隐藏实例变量UISwitch *privateSwitch的本地变量privateSwitch

switchToggled:操作中,您正在使用实例变量来测试交换机的状态,而不是cellForRowAtIndexPath中声明的状态。您可以使用sender参数,如下所示:

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

P.S:我会使用UIControlEventValueChanged代替UIControlEventTouchUpInside