如何获得NSWindow的默认标题栏高度?

时间:2015-03-10 03:05:43

标签: macos nswindow window-managers

我创建了一个OS / X应用程序,当它运行时,我将窗口放在屏幕的中心。为了做到这一点,我必须在计算y值时包含标题栏高度。

有没有办法确定默认标题栏?我希望(基于我对其他窗口系统的经验)我必须以某种方式查询窗口管理器......

3 个答案:

答案 0 :(得分:6)

我想出了这个解决方案。请注意,当窗口的styleMask包含fullSizeContentView时,会返回0.0,因为在这种情况下,标题栏实际上没有高度。

作为Swift扩展:

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

用法:

let titlebarHeight = someWindow.titlebarHeight

作为Objective-C类别扩展:

@implementation NSWindow (TitleBarHeight)

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

@end

用法:

CGFloat titlebarHeight = someWindow.titlebarHeight;

答案 1 :(得分:4)

目前尚不清楚是否要将内容矩形居中,然后构建框架矩形以使内容矩形居中,或者如果您想使框架矩形居中并且对相应的内容矩形感兴趣。< / p>

在任何一种情况下,NSWindow都有方法可以提供帮助。在拥有实例之前,您可以使用类方法+frameRectForContentRect:styleMask:+contentRectForFrameRect:styleMask:。这些考虑了样式蒙版表示的窗口样式,但不考虑最终窗口可能考虑的任何工具栏。

如果您正在使用现有实例,则可以使用方法-frameRectForContentRect:-contentRectForFrameRect:。那些使用窗口的当前样式并考虑其工具栏。 (工具栏在框架矩形内,但不在内容矩形内。)

您似乎决定使用屏幕的实际屏幕中心。但是,您应该考虑使用-center的{​​{1}}方法。它将窗口水平定位在中心,但实际上高于屏幕的真实垂直中心。它故意这样做,因为这对用户来说更加突出和直接。

答案 2 :(得分:0)

.fullSizeContentView上使用NSWindow时计算工具栏/标题栏区域的高度的答案

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

fullSizeContentViewNoContentAreaHeight是您想要的高度。 这对于动态计算该值很重要,因为如果您有一个使用NSDocument的应用程序,并且用户创建了新文档,则系统可能会在新标签页中打开该新文档。 您可以在updateViewConstraints()中执行此操作以检测这种更改。

来源:https://developer.apple.com/videos/play/wwdc2016/239/

相关问题