gpt4 book ai didi

objective-c - NSScrollView 检测滚动位置

转载 作者:行者123 更新时间:2023-12-03 16:23:08 24 4
gpt4 key购买 nike

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

[[_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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com