Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 995
Suppy Avatar asked Mar 10 '15 03:03

Suppy


2 Answers

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;
like image 90
Ky. Avatar answered Nov 15 '22 13:11

Ky.


Answer for computing the height of the toolbar/titlebar area when using .fullSizeContentView on NSWindow

if let windowFrameHeight = self.view.window?.contentView?.frame.height,
    let contentLayoutRectHeight = self.view.window?.contentLayoutRect.height {
    let fullSizeContentViewNoContentAreaHeight = windowFrameHeight - contentLayoutRectHeight
}

fullSizeContentViewNoContentAreaHeight is the height you want. This is important to compute this value dynamically, because if you have an app using NSDocument and if the user creates a new document, the system might open this new document in a new tab. You might do this in updateViewConstraints() to detect this kind of changes.

Source: https://developer.apple.com/videos/play/wwdc2016/239/

like image 38
vomi Avatar answered Nov 15 '22 14:11

vomi