1

我有一个UISwitch放在我的情节提要中并将其连接到我的实现文件中的插座,并将该valueChanged:方法连接到控制事件“值已更改”。但是,仅当我将其从关闭切换到打开时才调用它,而不是从打开到关闭。

这是我的代码:

视图控制器.h

@interface splitViewController : UIViewController
@property (weak, nonatomic) IBOutlet UISwitch *tipIncluded;

@end

视图控制器.m:

- (IBAction)valueChanged:(UISwitch *)sender {
    NSLog(@"3");
    if (_tipIncluded.isOn==YES){
        NSLog(@"2");
        _tipIncluded.on=NO;
        _tip.text=@"";
        _tip.backgroundColor = [UIColor whiteColor];

    }
    if (_tipIncluded.isOn==NO){
        NSLog(@"1");
        _tipIncluded.on=YES;
        _tip.text=@"0";
        _tip.backgroundColor = [UIColor lightGrayColor];
        _tip.textColor = [UIColor blackColor];
    }

}

我知道它仅在从关闭变为打开时才调用此方法,因为当我以这种方式切换时,我仅在方法结束时从 NSLog 中获取 3。

4

2 回答 2

5

永远不要将任何事情与“是”或“否”进行比较:

if (_tipIncluded.isOn==YES){
if (_tipIncluded.isOn==NO){

那个代码是错误的。UISwitch也没有isOn属性。

简化您的代码。只需说if (_tipIncluded.on)else(或if (!tipIncluded.on))。

你正在做的事情也很疯狂。用户将开关切换到 ON 的那一刻,您将立即将其切换到 OFF 反之亦然。这将使开关无法移动!

于 2013-04-02T23:11:09.053 回答
0

记住也要在开关上放一个插座。这对我有用。只需确保首先输入默认值即可。开也许。

[mySwitchOutlet setOn:YES animated:YES];

- (IBAction)mySwitch:(UISwitch *)sender {

    if ([sender isOn])
    {
         NSLog(@"ON");

    }else{
         NSLog(@"OFF");
    }

}
于 2013-04-02T23:39:40.070 回答