Update:
我原来的答案是完全错误的。
感谢 JWWalker 和 Wil Shipley 通过评论让我意识到这一点。
希望对于通过搜索来到这里的人们来说,这是一个更有帮助的答案:
Unlike UIScrollView
, NSScrollView
不提供委托方法来通知您视图何时滚动到顶部/底部。
要检测这些情况,您必须启用boundsDidChange
通知并订阅它们。
当收到边界更新时,您可以检查是否y
剪辑视图边界的坐标是0
(= 底部),或者剪辑视图边界的顶部边缘与文档视图对齐(= 顶部)。
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")
}
}
对于使用弹性滚动的滚动视图,更新会出现短暂的延迟,因为剪辑视图似乎推迟了边界更改通知,直到滚动弹跳完成。
您可以使用您的可见矩形NSScrollView
的 contentView 而不是边界:
- (void)boundsDidChangeNotification:(NSNotification*) notification
{
NSRect visibleRect = [[_scrollView contentView] documentVisibleRect];
NSLog(@"Visible rect:%@", NSStringFromRect(visibleRect));
NSPoint currentScrollPosition = visibleRect.origin;
}
内容视图边界在滚动期间不会更改,因此在原始代码中,bounds.origin 可能始终返回 0/0。