swift - 如何为 NSWindow 的标题栏着色

标签 swift macos cocoa nswindow

我需要将 NSWindow 的标题栏更改为红色。 当我更改背景颜色时,整个窗口都变成红色。

我只想更改标题背景颜色。

谢谢。

最佳答案

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

对于 View ,我只是这样做了:

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)
    }
}

然后这样安排:

enter image description here

使用这些窗口设置:

enter image description here

结果是:

enter image description here

小心;拥有权利的同时也被赋予了重大的责任。注意不要让红绿色盲的人难以使用界面。看看上面的图片,我可能会选择比 NSColor.red 更浅的红色,因为它的深色遮住了标题。但您可以对此进行试验,直到获得看起来不错的结果。

关于swift - 如何为 NSWindow 的标题栏着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47759424/

相关文章:

Swift - 从滑入式菜单中打开 UIViewController

swift - 在 cocoa 上处理鼠标事件时出错

ios - 滚动时 Collection View 单元格重复

ios - Type Any 没有下标成员(Array,Swift 3.0)

macos - Mac npm 出现 ENOENT 错误

xcode - 从一开始逐步逐步/最快的方法到在OS X上 “code sign”我的Qt应用程序是什么,以便可以分发?

ios - 我可以从 OS X 上的地址簿中获取一个人的显示名称或复合名称吗?

objective-c - NSMutableDictionary setObject : forKey - crashes 问题

objective-c - 来自另一个线程的回调中 NSAutoreleasePool 的最佳实践

ios - 我们可以使用按钮代替 Collection View 吗?