如何观察NSScroller的变化?

bas*_*ibe 4 cocoa key-value-observing nsscrollview

我有一个NSScrollView子类,我想NSView根据当前的滚动位置更新另一个.我试图KVC-观察value[self horizontalScroller],但从来没有被调用.

// In awakeFromNib
[[self horizontalScroller] addObserver:self
                            forKeyPath:@"value"
                               options:NSKeyValueObservingOptionNew
                               context:NULL];

// Later in the file
- (void)observeValueForKeyPath:(NSString *)keyPath 
                  ofObject:(id)object 
                    change:(NSDictionary *)change 
                   context:(void *)context {
    if (object == [self horizontalScroller] && [keyPath isEqualToString:@"value"]) {
        // This never gets called
    }
}
Run Code Online (Sandbox Code Playgroud)

您是否在我的推理中看到错误或者知道如何观察滚动的更好方法NSScrollview

小智 7

告诉滚动视图的内容视图发布已更改的通知,然后侦听NSViewBoundsDidChangeNotification.

[[aScrollView contentView] setPostsBoundsChangedNotifications:YES];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(boundsDidChangeNotification:)
                                             name:NSViewBoundsDidChangeNotification
                                           object:[scrollView contentView]];
Run Code Online (Sandbox Code Playgroud)

如" 滚动视图编程指南"中所述,您可以通过以下方式获取当前滚动位置:

NSPoint currentScrollPosition = [[theScrollView contentView] bounds].origin;
Run Code Online (Sandbox Code Playgroud)