代码之家  ›  专栏  ›  技术社区  ›  bastibe

如何观察nsscroller的变化?

  •  4
  • bastibe  · 技术社区  · 14 年前

    我有一个 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
        }
    }
    

    你在我的推理中看到错误还是知道更好的方法来观察 NSScrollview ?

    1 回复  |  直到 14 年前
        1
  •  7
  •   user155959    14 年前

    告诉滚动视图的内容视图发布边界更改通知,然后侦听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;
    
    推荐文章