UISwitch在以编程方式更改时不发送valueChanged事件

rob*_*era 7 objective-c uiswitch ios

我有一对UISwitch通过valueChanged事件连接到IBAction.触摸开关时,valueChanged事件正常触发.但是,如果我以编程方式更改其中一个开关,则不会调用我的IBAction.

- (IBAction)switchChanged:(UISwitch *)sender {
    if (sender == self.shippingSwitch) {
        if (self.shippingSwitch.on && !self.PayPalSwitch.on) {
            [self.PayPalSwitch setOn:YES animated:YES];
        }
    }

    if (sender == self.PayPalSwitch) {
        if (!self.PayPalSwitch.on) {
            // This is not working when the PayPal switch is set via the code above
            self.PayPalEmailField.backgroundColor = [UIColor grayColor];
            self.PayPalEmailField.enabled = NO;

            if (self.shippingSwitch.on) {
                [self.shippingSwitch setOn:NO animated:YES];
            }
        } else {
            self.PayPalEmailField.backgroundColor = [UIColor clearColor];
            self.PayPalEmailField.enabled = YES;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

rma*_*ddy 9

这是正确和理想的行为.由于您明确更改了值,因此您可以决定如何处理更改的值.

这样做的原因是,在通知用户通过用户交互更改其值后,显式更改控件的值并不罕见.如果显式状态更改导致事件再次触发,则最终会进入无限循环.