如何像在“预览”中一样将NSView置于NSScrollView中心?
答案 0 :(得分:11)
阅读有关滚动到特定位置的Scroll View Programming Guide部分。有顶部或底部的例子。您只需更改数学以根据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];
}
答案 1 :(得分:0)
在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)
}
}