objective-c - NSScrollView 检测滚动位置

标签 objective-c cocoa nstableview nsscrollview

当滚动到底部时如何检测滚动位置?

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





- (void) boundsDidChangeNotification: (NSNotification *) notification
{
    NSPoint currentScrollPosition = [[_scrollView contentView] bounds].origin;
}

最佳答案

更新:
我原来的答案是完全错误的。
感谢 JWWalker 和 Wil Shipley 通过评论让我意识到这一点。

对于通过搜索来到这里的人们来说,这是一个希望更有帮助的答案:
不像 UIScrollView , NSScrollView不提供委托(delegate)方法来通知您 View 何时滚动到顶部/底部。
要检测这些情况,您必须启用 boundsDidChange通知并订阅它们。

当收到边界更新时,您可以检查 y 是否剪辑 View 边界的坐标是 0 (= 底部),或者剪辑 View 边界的顶部边缘与文档 View 对齐 (= 顶部)。

private func configureScrollView() {
        self.scrollView.contentView.postsBoundsChangedNotifications = true
        NotificationCenter.default.addObserver(self, selector: #selector(contentViewDidChangeBounds), name: NSView.boundsDidChangeNotification, object: self.scrollView.contentView)
    }

@objc
func contentViewDidChangeBounds(_ notification: Notification) {
    guard let documentView = scrollView.documentView else { return }

    let clipView = scrollView.contentView
    if clipView.bounds.origin.y == 0 {
        print("bottom")
    } else if clipView.bounds.origin.y + clipView.bounds.height == documentView.bounds.height {
        print("top")
    }
}

对于使用弹性滚动的 ScrollView ,更新会出现短暂的延迟,因为剪辑 View 似乎会推迟边界更改通知,直到滚动弹跳完成。

<罢工> 您可以使用 NSScrollView 的可见矩形的 contentView 而不是边界:

- (void)boundsDidChangeNotification:(NSNotification*) notification
{
    NSRect visibleRect = [[_scrollView contentView] documentVisibleRect];
    NSLog(@"Visible rect:%@", NSStringFromRect(visibleRect));
    NSPoint currentScrollPosition = visibleRect.origin;
}

内容 View 边界在滚动过程中不会改变,因此在原始代码中,bounds.origin 可能始终返回 0/0。

关于objective-c - NSScrollView 检测滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23127183/

相关文章:

Objective-C 堆栈跟踪

ios - 使用 MFMailComposeViewController 打开 presentModalViewController 时崩溃

cocoa - 如何在没有动画的情况下滚动RowToVisible

objective-c - 如何检索 NSPopUpButton 单元格的当前选择?

ios - YTPlayerView缩略图自定义大小

objective-c - 在 iCal 上获取/设置日历事件(以编程方式)

macos - 在 SpriteKit 中使用 NSButton

swift - 如何防止 MacOS WebView 在点击选项卡后失去第一响应者?

macos - 多个 NSTableViews 选择

swift - NSTableView 获取具有单元格的 indexPath