uch*_*aka 15 cocoa nsscrollview centering nsclipview
有很多关于如何让NSScrollView集中其文档视图的例子.这里有两个例子(它们是如此相似,以至于有人在没有归属的情况下复制某人,但关键是如何.) http://www.bergdesign.com/developer/index_files/88a764e343ce7190c4372d1425b3b6a3-0.html https:// github的.com/devosoft/avida /斑点/主/应用/观察者的MacOS/SRC /主/ CenteringClipView.h
这通常通过子类化NSClipView并覆盖来完成:
- (NSPoint)constrainScrollPoint:(NSPoint)newOrigin;
但是在Mac OS X 10.9 +中不推荐使用此方法
我们现在能做什么?哦不!〜
uch*_*aka 23
嗯,答案很简单,没有那么臃肿.无论如何,这些都不适用于双击放大.
这样做.它只是有效.您还可以根据需要自定义调整.
在@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;
}
Run Code Online (Sandbox Code Playgroud)
在@interface中只需添加一个属性.这允许您不使用居中.可以想象,有时可能会出现条件逻辑.
@property BOOL centersDocumentView;
此外,请务必将此设置BOOL为YES或NO覆盖
initWithFrame 和 initWithCoder:
所以你将拥有一个已知的默认值.
(记住小孩, initWithCoder:允许你做必要的事情并在笔尖中设置视图的类.不要忘记在你的东西之前打电话给super!)
当然,如果你需要支持10.9之前的任何东西,你需要实现其他的东西.
(虽然可能没有其他人那么多......)
pra*_*mil 17
这里是swift的工人阶级
class CenteredClipView:NSClipView
{
override func constrainBoundsRect(proposedBounds: NSRect) -> NSRect {
var rect = super.constrainBoundsRect(proposedBounds)
if let containerView = self.documentView as? NSView {
if (rect.size.width > containerView.frame.size.width) {
rect.origin.x = (containerView.frame.width - rect.width) / 2
}
if(rect.size.height > containerView.frame.size.height) {
rect.origin.y = (containerView.frame.height - rect.height) / 2
}
}
return rect
}
}
Run Code Online (Sandbox Code Playgroud)