如何在窗口中固定图层(视图)

时间:2013-11-19 12:30:08

标签: layout calayer autolayout nswindow

想象一下在其父图层(它是图层支持CALayer的根图层)中绘制的黄色框(NSView实例)。

当父视图的框架发生变化时,黄色框应保持在屏幕上的相同位置。当我将自动调整面具设置为NSViewMinXMargingNSViewMaxXMarging时,黄色框会在屏幕上按比例在更改视图宽度之间移动...

如何在保持子图层初始位置的同时调整NSWindowNSView)的边框?

我了解- (void)layoutSublayersOfLayer:(CALayer *)layer CALayerDelegate方法,但我不知道如何实现此行为。

以下是演示:

enter image description here

1 个答案:

答案 0 :(得分:0)

这是我的方法。 子类NSWindow。

.H-文件:

#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>

@interface NNMainWindow : NSWindow <NSWindowDelegate> {

    CALayer* yellowLayer;

    NSRect leftEdge;
    NSRect rightEdge;
    NSRect topEdge;
    NSRect bottomEdge;
}
@end

的.m-文件:

#import "NNMainWindow.h"

@implementation NNMainWindow

- (void)awakeFromNib {

    //Add yellow layer here....

    [self setAcceptsMouseMovedEvents:YES];

    [self updateResizingMarkers];
}

- (void)updateResizingMarkers {
    NSSize horizontalRectSize = NSMakeSize(NSWidth(self.frame), 8.f);
    horizontalRectSize.width += 10.f;
    NSSize verticalRectSize = NSMakeSize(8.f, NSHeight(self.frame));
    verticalRectSize.height += 10.f;

    leftEdge = NSZeroRect;
    leftEdge.size = verticalRectSize;
    leftEdge.origin = NSMakePoint(-5.f, -5.f);

    rightEdge = NSZeroRect;
    rightEdge.size = verticalRectSize;
    rightEdge.origin = NSMakePoint(horizontalRectSize.width - 10.f - 3.f, -5.f);
}

- (void)mouseMoved:(NSEvent *)theEvent {

    NSPoint currentLocation = [theEvent locationInWindow];

    if (NSPointInRect(currentLocation, leftEdge))
        yellowLayer.autoresizingMask = kCALayerMinXMargin;

    if (NSPointInRect(currentLocation, rightEdge))
        yellowLayer.autoresizingMask = kCALayerMaxXMargin;
}

- (void)windowDidResize:(NSNotification *)notification {
    [self updateResizingMarkers];
}

@end