UISwitch在以编程方式更改时不发送valueChanged事件 [英] UISwitch Doesn't Send valueChanged Event When Changed Programmatically

查看:393
本文介绍了UISwitch在以编程方式更改时不发送valueChanged事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a pair of UISwitches hooked up to a IBAction via the valueChanged event. The valueChanged event is firing fine when the switches are touched. However, if I change one of the switches programmatically it doesn't call my 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;
        }
    }
}


推荐答案

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

This is correct and desired behavior. Since you explicitly changed the value, it is up to you to decide how to handle the changed value.

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

The reason for this is because it is not uncommon to explicitly change the value of control after being notified of its value being changed through user interaction. If the explicit state change caused the event to fire again, you would end up in an infinite loop.

这篇关于UISwitch在以编程方式更改时不发送valueChanged事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆