2010-04-22 81 views
4

我有一個NSScrollView子類,我想根據當前的滾動位置更新另一個NSView。我試過KVC-觀察的value,但那個永遠不會被調用。如何觀察NSScroller的變化?

// 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的滾動更好的方法?

回答

6

告訴滾動視圖的內容視圖來發布界面更改通知,然後監聽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;