简体   繁体   中英

Key-value observing doesn't work for zoomScale

I'm stuck with following problem. I have a UIScrollView, _myScrollView, and I want to have another UIScrollView following it's movements. So I'm using key-value observing for the properties "zoomScale" and "contentOffset", but the observeValueForKeyPath:ofObject:change:context: method only report changes in "contentOffset", not in "zoomScale", though the zooming workes fine. (See code snippet below.) What could be the reason for this?

-(void)viewDidLoad {
    ...
    [_myScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:NULL];
    [_myScrollView addObserver:self forKeyPath:@"zoomScale" options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"zoomScale"]) {
        NSLog(@"zoomScale: %@", change); // Never gets called
    }
    ...
}

The zoomScale property isn't KVO compliant. But UIScrollViewDelegate has a scrollViewDidZoom method that you can use to track changes to zoomScale.

UIKit actually doesn't support KVO.

From the docs :

Note: Although the classes of the UIKit framework generally do not support KVO you can still implement it in the custom objects of your application, including custom views.

It does work sometimes (as you've seen), but support for it is undocumented and inconsistent. Use the delegate methods instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM