Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

center programmatically created window

I've been using the example from here to create a custom titlebar-less window:

Drawing a custom window on Mac OS X

I've found this is the only way i can create a titlebar-less window in Leopard, Snow Leopard and Lion, other methods don't work right either on Leopard or Lion. (If i try to invoke a titlebar-less window via normal NSWindow and IB, it won't start up in Leopard anymore)

So far this custom titlebar-less window works great everywhere, but i can't center it, only a hard fixed position in Interface Builder.

It's fairly easy to center a normal NSWindow *window implementation with [window center], but i've found nothing that works on this custom window subclass, a window that isn't created from nib via Interface Builder.

I've tried a few things from NSWindow, but nothing seems to work.

Any Ideas?

like image 479
devilhunter Avatar asked Apr 15 '11 21:04

devilhunter


4 Answers

extension NSWindow {
    public func setFrameOriginToPositionWindowInCenterOfScreen() {
        if let screenSize = screen?.frame.size {
            self.setFrameOrigin(NSPoint(x: (screenSize.width-frame.size.width)/2, y: (screenSize.height-frame.size.height)/2))
        }
    }
}
like image 158
Klaas Avatar answered Oct 15 '22 04:10

Klaas


Objective - C in macOS Catalina , Version 10.15.3

more readable @Wekwa's answer

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSWindow * window = NSApplication.sharedApplication.windows[0];
    CGFloat xPos = NSWidth(window.screen.frame)/2 - NSWidth(window.frame)/2;
    CGFloat yPos = NSHeight(window.screen.frame)/2 - NSHeight(window.frame)/2;
    [window setFrame:NSMakeRect(xPos, yPos, NSWidth(window.frame), NSHeight(window.frame)) display:YES];
}
like image 23
dengST30 Avatar answered Oct 15 '22 02:10

dengST30


CGFloat xPos = NSWidth([[window screen] frame])/2 - NSWidth([window frame])/2;
CGFloat yPos = NSHeight([[window screen] frame])/2 - NSHeight([window frame])/2;
[window setFrame:NSMakeRect(xPos, yPos, NSWidth([window frame]), NSHeight([window frame])) display:YES];

This puts it at the literal center of the screen, not taking into account the space occupied by the dock and menu bar. If you want to do that, change [[window screen] frame] to [[window screen] visibleFrame].

like image 41
Wekwa Avatar answered Oct 15 '22 03:10

Wekwa


The question should probably be why [window center] does not work; but assuming that is the case use NSScreen to get the screen coordinates, do the math, and center the window directly.

like image 42
CRD Avatar answered Oct 15 '22 02:10

CRD