4

我有一个NSScrollView子类,我想NSView根据当前滚动位置更新另一个。我尝试过 KVC 观察valueof[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
    }
}

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

4

1 回答 1

7

告诉滚动视图的内容视图发布边界更改通知,然后监听 NSViewBoundsDidChangeNotification。

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

Scroll View Programming Guide中所述,您可以通过以下方式获取当前滚动位置:

NSPoint currentScrollPosition = [[theScrollView contentView] bounds].origin;
于 2010-04-22T21:12:03.573 回答