开发者

KVO not working with UISwitch

开发者 https://www.devze.com 2023-03-30 23:35 出处:网络
For the life of me I can\'t get KVO working with UISwitch. I have a custom UITableViewCell witha UISwitch added through Interface Builder. I created an IBOutlet for the UISwitch and linked it to theSw

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");
}

obser开发者_开发百科veValueForKeyPath:ofObject:change:context is never called!


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消