Reputation: 2340
Short and sweet: How can I tell Interface Builder to center a window on a user's screen? I've seen the positioning tool on the inspector, but eyeballing doesn't always land as squarely as I like. Is this something where I should switch over to Xcode and add something to the init
or awakeFromNib
methods?
Upvotes: 6
Views: 6210
Reputation: 2042
I was working on a React Native MacOS project and had to center the window but the [self.window center];
approach only works for horizontally, not vertically. So one of the comments made me realize that we can also center it by getting the screen size and subtracting the app width then dividing by two. So here's a working version.
AppDelegate.mm
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
// You can add your custom initial props in the dictionary below.
// They will be passed down to the ViewController used by React Native.
self.initialProps = @{};
// Call the super method to continue application launch
[super applicationDidFinishLaunching:notification];
// Define window width and height
CGFloat windowWidth = 1000;
CGFloat windowHeight = 600;
// Get screen size
NSScreen *screen = [NSScreen mainScreen];
NSRect screenRect = [screen frame];
// Calculate the center position
CGFloat xPos = (screenRect.size.width - windowWidth) / 2;
CGFloat yPos = (screenRect.size.height - windowHeight) / 2;
// Set the initial window size and position here
NSRect frame = NSMakeRect(xPos, yPos, windowWidth, windowHeight);
[self.window setFrame:frame display:YES];
// Make sure the window is initialized and displayed before centering
[self.window makeKeyAndOrderFront:nil];
}
Upvotes: 0
Reputation: 2463
Use [window center];
for the centre of the window to be centred to the screen.
Also, assuming you're in 10.5+, there is a centre to screen button in Interface Builder.
Upvotes: 7
Reputation: 7764
For macOS Mojave this worked for me, in AppDelegate
applicationDidFinishLaunching
for the Main Window:
[[[NSApplication sharedApplication] mainWindow] center];
Upvotes: 0
Reputation: 150685
You could use [window center]
as answered by wahkiz, but that might not be exactly what you want. The documentation states that this will put the window centered horizontally, but somewhat above the vertical centre. In this way the window has a visual prominence.
If you want to put your window in the exact centre, then manual positioning (as commented by Koning Baard XIV) will work for you.
Upvotes: 15
Reputation: 616
In your appdelegate, in applicationfinishedlaunching, add this code at the bottom.
[window center];
Upvotes: 3