UISwitch只能单向工作

die*_*con 1 uiswitch ios

我有一个UISwitch放在我的故事板中并将其连接到我的实现文件中的插座,并将该valueChanged:方法连接到控制事件"值已更改".但是,只有在我将其从关闭切换为开启时才会调用,而不是从开启切换到关闭.

这是我的代码:

ViewController.h

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

@end
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

我知道它只是在从off变为on时才调用这个方法,因为当我以这种方式切换时,我只在方法结束时从NSLog获得3.

mat*_*att 5

切勿与YES或NO进行比较:

if (_tipIncluded.isOn==YES){
if (_tipIncluded.isOn==NO){
Run Code Online (Sandbox Code Playgroud)

那段代码错了.也没有isOnUISwitch的财产.

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

你所做的也是坚果.用户将开关切换到ON 的瞬间,您立即将其切换为OFF ,反之亦然.这将无法移动开关!