NSView 在 NSScrollView 中居中

发布于 2024-08-11 11:15:28 字数 44 浏览 3 评论 0原文

如何像“预览”那样将 NSView 在 NSScrollView 中居中?

How do I center an NSView within an NSScrollView like the way "Preview" does?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

残龙傲雪 2024-08-18 11:15:28

阅读 滚动视图编程指南部分介绍了滚动到特定位置。有顶部或底部的示例。您只需更改数学即可根据 NSView 的中间计算原点。像这样的东西:

-(void)scrollToCenter:(NSScrollView*)scrollView
{
    const CGFloat midX = NSMidX([[scrollView documentView] bounds]);
    const CGFloat midY = NSMidY([[scrollView documentView] bounds]);

    const CGFloat halfWidth = NSWidth([[scrollView contentView] frame]) / 2.0;
    const CGFloat halfHeight = NSHeight([[scrollView contentView] frame]) / 2.0;

    NSPoint newOrigin;
    if([[scrollView documentView] isFlipped])
    {
        newOrigin = NSMakePoint(midX - halfWidth, midY + halfHeight);
    }
    else
    {
        newOrigin = NSMakePoint(midX - halfWidth, midY - halfHeight);
    }

    [[scrollView documentView] scrollPoint:newOrigin];
}

Read the Scroll View Programming Guide section on scrolling to a specific position. There are examples there for top or bottom. You'd just change the math to calculate the origin based on middle of your NSView. Something like:

-(void)scrollToCenter:(NSScrollView*)scrollView
{
    const CGFloat midX = NSMidX([[scrollView documentView] bounds]);
    const CGFloat midY = NSMidY([[scrollView documentView] bounds]);

    const CGFloat halfWidth = NSWidth([[scrollView contentView] frame]) / 2.0;
    const CGFloat halfHeight = NSHeight([[scrollView contentView] frame]) / 2.0;

    NSPoint newOrigin;
    if([[scrollView documentView] isFlipped])
    {
        newOrigin = NSMakePoint(midX - halfWidth, midY + halfHeight);
    }
    else
    {
        newOrigin = NSMakePoint(midX - halfWidth, midY - halfHeight);
    }

    [[scrollView documentView] scrollPoint:newOrigin];
}
温馨耳语 2024-08-18 11:15:28

在斯威夫特中:

extension NSScrollView {
    func scrollToCenter() {
        guard let docView = documentView else { return }
        let center = CGPoint(
            x: docView.bounds.midX - contentView.frame.width / 2,
            y: docView.bounds.midY - (docView.isFlipped ? -1 : 1) * contentView.frame.height / 2
        )
        docView.scroll(center)
    }
}

In Swift:

extension NSScrollView {
    func scrollToCenter() {
        guard let docView = documentView else { return }
        let center = CGPoint(
            x: docView.bounds.midX - contentView.frame.width / 2,
            y: docView.bounds.midY - (docView.isFlipped ? -1 : 1) * contentView.frame.height / 2
        )
        docView.scroll(center)
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文