KVO无法与UISwitch一起使用 [英] KVO not working with UISwitch

查看:133
本文介绍了KVO无法与UISwitch一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一生中,我无法让KVO与UISwitch一起工作.我有一个自定义UITableViewCell,其中包含通过Interface Builder添加的UISwitch.我为UISwitch创建了一个IBOutlet并将其链接到theSwitch变量.

For the life of me I can't get KVO working with UISwitch. I have a custom UITableViewCell with a UISwitch added through Interface Builder. I created an IBOutlet for the UISwitch and linked it to theSwitch variable.

- (id)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
           [theSwitch addObserver:self forKeyPath:@"on" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"toggled switch");
}

从未调用observeValueForKeyPath:ofObject:change:context!

observeValueForKeyPath:ofObject:change:context is never called!

推荐答案

我不确定,但是UISwitch可能完全不符合KVO.

I'm not sure, but it's possible that UISwitch simply isn't KVO-compliant.

没关系,因为您只能使用控制事件:

No matter, because you can just use control events:

[theSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
// ...
- (void)switchChanged:(UISwitch *)sender {
    if (sender.on) {
        // ...
    }
}

这篇关于KVO无法与UISwitch一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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