KVO不与UISwitch合作

Jay*_* Q. 4 key-value-observing uiswitch ios

对于我的生活,我无法让KVO与UISwitch合作.我有一个自定义UITableViewCell,通过Interface Builder添加了UISwitch.我为UISwitch创建了一个IBOutlet并将其链接到theSwitch变量.

- (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");
}
Run Code Online (Sandbox Code Playgroud)

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

jtb*_*des 10

我不确定,但UISwitch可能不符合KVO标准.

无论如何,因为你可以只使用控制事件:

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