嗯,答案很简单,而且远没有那些过于臃肿。无论如何,这些都不适用于双击放大。
这样做。它只是工作。您还可以根据需要自定义调整。
在@implementation 中,您只需要实现对constrainBoundsRect 的覆盖:
- (NSRect)constrainBoundsRect:(NSRect)proposedClipViewBoundsRect {
NSRect constrainedClipViewBoundsRect = [super constrainBoundsRect:proposedClipViewBoundsRect];
// Early out if you want to use the default NSClipView behavior.
if (self.centersDocumentView == NO) {
return constrainedClipViewBoundsRect;
}
NSRect documentViewFrameRect = [self.documentView frame];
// If proposed clip view bounds width is greater than document view frame width, center it horizontally.
if (proposedClipViewBoundsRect.size.width >= documentViewFrameRect.size.width) {
// Adjust the proposed origin.x
constrainedClipViewBoundsRect.origin.x = centeredCoordinateUnitWithProposedContentViewBoundsDimensionAndDocumentViewFrameDimension(proposedClipViewBoundsRect.size.width, documentViewFrameRect.size.width);
}
// If proposed clip view bounds is hight is greater than document view frame height, center it vertically.
if (proposedClipViewBoundsRect.size.height >= documentViewFrameRect.size.height) {
// Adjust the proposed origin.y
constrainedClipViewBoundsRect.origin.y = centeredCoordinateUnitWithProposedContentViewBoundsDimensionAndDocumentViewFrameDimension(proposedClipViewBoundsRect.size.height, documentViewFrameRect.size.height);
}
return constrainedClipViewBoundsRect;
}
CGFloat centeredCoordinateUnitWithProposedContentViewBoundsDimensionAndDocumentViewFrameDimension
(CGFloat proposedContentViewBoundsDimension,
CGFloat documentViewFrameDimension )
{
CGFloat result = floor( (proposedContentViewBoundsDimension - documentViewFrameDimension) / -2.0F );
return result;
}
在@interface 中只需添加一个属性。这使您可以不使用居中。可以想象,有时您可能想要关闭居中的条件逻辑。
@property BOOL centersDocumentView;
另外,请务必将其设置BOOL
为YES
或NO
覆盖
initWithFrame
和initWithCoder:
所以你会有一个已知的默认值来工作。
(记住孩子们, initWithCoder:
让你做必要的事情并在笔尖中设置视图的类。不要忘记在你的东西之前调用 super!)
当然,如果您需要支持早于 10.9 的任何内容,则需要实现其他内容。
(虽然可能没有其他人那么多......)
编辑:正如其他人所指出的,Apple 在https://developer.apple.com/library/archive/samplecode/Exhibition/Listings/Exhibition_CenteringClipView_swift有 Swift 中的示例代码(尽管从 2016 年开始,所以它可能不是当前的 Swift :D) .html