KVO not working with UISwitch

人走茶凉 提交于 2020-04-10 14:07:41

问题


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 is never called!


回答1:


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) {
        // ...
    }
}



回答2:


theSwitch might not have been initialized when you add the observer. try adding the observer in awakeFromNib.



来源:https://stackoverflow.com/questions/7193958/kvo-not-working-with-uiswitch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!