Home > Software engineering >  Set aspectRatio of the main window on MacOS
Set aspectRatio of the main window on MacOS

Time:10-27

I need to make main window to preserve width/height ratio when the user resizes it on MacOS.

My first idea was to handle the following notification:

@interface Override_iOS : NSObject
@end

__strong Override_iOS *_instance;
@implementation Override_iOS
 (void)load
{
    NSLog(@"[Override_iOS load]");
    _instance = [Override_iOS new];
    [[NSNotificationCenter defaultCenter] addObserver:_instance
                                            selector:@selector(applicationDidFinishLaunching:)
                                                name:UIApplicationDidFinishLaunchingNotification
                                            object:nil];
}
-(void)applicationDidFinishLaunching:(NSNotification*) notification
{
    NSLog(@"[Override_iOS applicationDidFinishLaunching:%@]", notification);
    //qDebug() << "applicationDidFinishLaunching handler";
}
@end

and try to set something like aspectRatio property of the main window, but looks like that this code would not work on MacOS, but only on iOS (at least in my app).

Is it possible to do something like this on MacOS?

Is there an option in XCode project?

EDIT1

I need something like enter image description here

CodePudding user response:

I have done very little with MacOS apps, but this may be what you're looking for...

Create a NSWindow subclass:

MyWindowController.h

#import <Cocoa/Cocoa.h>

NS_ASSUME_NONNULL_BEGIN

@interface MyWindowController : NSWindowController

@end

NS_ASSUME_NONNULL_END

MyWindowController.m

#import "MyWindowController.h"

@interface MyWindowController ()
@end

@implementation MyWindowController

- (void)windowDidLoad {
    [super windowDidLoad];
    // set the aspect ratio here
    [self.window setAspectRatio:NSMakeSize(320.0, 640.0)];
}

@end

Then assign the custom class of your window controller:

enter image description here

  • Related