cocoa — getting nested NSViews and CALayers to resize proportionally

跟風遠走 提交于 2019-12-07 17:47:45

问题


My NSWindow's contentView is an NSView subclass. It has some other NSView subclasses as subviews. The subviews are layer-based, and those layers in turn contain sublayers. Some of the sublayers have further sub-sublayers.

I want the whole thing to resize proportionally when the window is resized. What is the right way to set it up so that will happen?

Thanks

EDIT: I am not using Interface Builder at all.


回答1:


Here's what I've done to get the contents of an NSView to scale proportionally as I resize the parent window. First, in interface builder, I added my NSView to the window, then added a reference to it in my AppDelegate. Mine happens to be called scrollView. I removed all of the auto-sizing behaviour from the scrollView.

Then, in my AppDelegate I added this:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // keep the aspect ratio constant so that the content looks good
    [window setContentAspectRatio:NSMakeSize(2, 1)];
    window.delegate = self;
}

- (void)windowDidResize:(NSNotification *)notification {
    // size the scrollView to fill the window, but keep its bounds constant
    NSRect rect = [[window contentView] frame];
    NSRect oldBounds = [scrollView bounds];
    [scrollView setFrame:rect];
    [scrollView setBounds:oldBounds];
}

This turns the AppDelegate into the window delegate too. Fine since I've not got much logic in it. By keeping the bounds constant while changing the frame, the contents of scrollView will be scaled down smoothly.



来源:https://stackoverflow.com/questions/4640586/cocoa-getting-nested-nsviews-and-calayers-to-resize-proportionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!