cocoa — getting nested NSViews and CALayers to resize proportionally

只愿长相守 提交于 2019-12-05 23:03:12

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.

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