How do I get default title bar height of a NSWindow?

Suppy picture Suppy · Mar 10, 2015 · Viewed 8k times · Source

I created an OS/X app that when it runs, I position the window in the center of the screen. In order to do this, it's essential that I include the title bar height in my calculation of the y value.

Is there a way to determine the default title bar? I'd expect (based on my experience with other windowing systems) that I have to query the window manager somehow...

Answer

Ben Leggiero picture Ben Leggiero · Apr 28, 2017

I've come up with this solution. Note that when the window's styleMask includes fullSizeContentView, this returns 0.0, because in that case the titlebar effectively has no height.

As a Swift extension:

extension NSWindow {
    var titlebarHeight: CGFloat {
        frame.height - contentRect(forFrameRect: frame).height
    }
}

Usage:

let titlebarHeight = someWindow.titlebarHeight

As an Objective-C Category-Extension:

@implementation NSWindow (TitleBarHeight)

- (CGFloat) titlebarHeight
{
    return self.frame.size.height - [self contentRectForFrameRect: self.frame].size.height;
}

@end

Usage:

CGFloat titlebarHeight = someWindow.titlebarHeight;