NSScrollView检测滚动位置 [英] NSScrollView detect scroll position
问题描述
当底部滚动时如何检测位置滚动?
How can i detect scroll of position when the scroll at bottom?
[[_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通过评论使我意识到了这一点。
Update:
My original answer was plain wrong.
Thanks to JWWalker and Wil Shipley for making me aware of that via comments.
对于希望通过搜索来到这里的人们来说,这是一个更有希望的答案:
与 UIScrollView
不同, NSScrollView
不提供委托方法来通知您何时视图滚动到顶部/底部。
要检测到这些情况,必须启用 boundsDidChange
通知并订阅。
Here's a hopefully more helpful answer for people coming here via search:
Unlike UIScrollView
, NSScrollView
does not provide a delegate method to inform you when a view was scrolled to top/bottom.
To detect those situations, you have to enable boundsDidChange
notifications and subscribe to them.
收到边界更新时,您可以检查剪辑视图边界的 y
坐标是否为 0
(=底部),或者剪辑视图边界的上边缘与文档视图(=顶部)对齐。
When receiving a bounds update, you can check if the y
coordinate of the clip view bounds is 0
(= bottom), or if the top edge of the clip view bounds aligns with the document view (= top).
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")
}
}
对于使用弹性滚动的滚动视图,更新会短暂延迟,因为剪辑视图似乎将边界更改通知推迟到滚动弹跳完成之前。
For scroll views that use elastic scrolling, the updates come with a short delay because the clip view seems to defer the bounds change notifications until the scroll bounce has finished.
您可以使用<$ c $的可见矩形c> NSScrollView 的contentView而不是范围:
You can use the visible rect of your NSScrollView
's contentView instead of the bounds:
- (void)boundsDidChangeNotification:(NSNotification*) notification
{
NSRect visibleRect = [[_scrollView contentView] documentVisibleRect];
NSLog(@"Visible rect:%@", NSStringFromRect(visibleRect));
NSPoint currentScrollPosition = visibleRect.origin;
}
内容视图范围在滚动过程中不会改变,因此在原始代码中,bounds.origin可能始终返回0/0。
The content view bounds don't change during scrolling, so in your original code, the bounds.origin probably always returns 0/0.
这篇关于NSScrollView检测滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!