Swift 如何给窗口的标题栏上色

Swift 如何给窗口的标题栏上色,swift,macos,cocoa,nswindow,Swift,Macos,Cocoa,Nswindow,我有一个要求,改变标题栏的国家统计局窗口的红色。 当我改变背景颜色时,整个窗口都变成红色 我只想更改标题的背景色 谢谢。在界面生成器的窗口属性检查器中,打开“透明标题栏”和“全尺寸内容视图”选项。然后,在窗口内容视图的顶部放置一个红色视图,它应该显示在标题栏后面 对于视图,我只是这样做: class RedView: NSView { // draw is simple; just fill the rect with red override func draw(_ dirty

我有一个要求,改变标题栏的国家统计局窗口的红色。 当我改变背景颜色时,整个窗口都变成红色

我只想更改标题的背景色


谢谢。

在界面生成器的窗口属性检查器中,打开“透明标题栏”和“全尺寸内容视图”选项。然后,在窗口内容视图的顶部放置一个红色视图,它应该显示在标题栏后面

对于视图,我只是这样做:

class RedView: NSView {
    // draw is simple; just fill the rect with red
    override func draw(_ dirtyRect: NSRect) {
        NSColor.red.set() // maybe experiment to find a better-looking shade of red
        dirtyRect.fill()
    }

    // provide an intrinsic content size, to make our view prefer to be the same height
    // as the title bar.
    override var intrinsicContentSize: NSSize {
        guard let window = self.window, let contentView = window.contentView else {
            return super.intrinsicContentSize
        }

        // contentView.frame is the entire frame, contentLayoutRect is the part not
        // overlapping the title bar. The difference will therefore be the height
        // of the title bar.
        let height = NSHeight(contentView.frame) - NSHeight(window.contentLayoutRect)

        // I just return noIntrinsicMetric for the width since the edge constraints we set
        // up in IB will override whatever we put here anyway
        return NSSize(width: NSView.noIntrinsicMetric, height: height)
    }
}
并这样安排:

使用这些窗口设置:

因此:


小心;权力越大,责任越大。注意不要让红绿色盲患者难以使用界面。看看上面的图片,我可能会选择比NSColor.red更浅的红色,因为它的黑暗使标题有点模糊。但是你可以尝试一下,直到你得到一个看起来不错的东西。

我用的不是故事板,而是XIB。我无法获得透明的标题栏。在外观部分不存在。请guide@RaghunathSahoo在XIB或故事板中选择窗口时,我会看到这些选项。您使用的是Xcode 9还是旧版本?我使用的是8.3.3,您可以升级到Xcode 9吗?如果没有,您可以在代码中设置窗口,方法是设置其
titlebarAppearsTransparent
styleMask
属性。@RaghunathSahoo回顾过去,最好使用
contentLayoutRect
以编程方式设置
RedView
的高度,而不是将其硬编码为23。我们可以这样做:1)在视图中实现
intrinsicContentSize
,2)将垂直内容拥抱和压缩阻力都设置为1000,以便强制使用固有高度,以及3)在IB中设置占位符大小,以便关闭歧义警告。这将使视图的大小与标题栏的大小相同,即使苹果在未来的macOS版本中更改了标题栏的大小。我已经更新了答案。到目前为止,答案不是一个很好的解决方案。这是黑客和易于视觉上不可接受的妥协。相反,您应该看看
NSAppearance
API,可能还有这个开源: