9

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

4

2 回答 2

11

阅读有关滚动到特定位置的滚动视图编程指南部分。有顶部或底部的示例。您只需更改数学以根据 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];
}
于 2009-11-21T00:40:25.080 回答
1

在斯威夫特:

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)
    }
}
于 2018-11-13T14:49:52.253 回答