我需要将 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)
}
}
然后这样安排:
使用这些窗口设置:
结果是:
小心;拥有权利的同时也被赋予了重大的责任。注意不要让红绿色盲的人难以使用界面。看看上面的图片,我可能会选择比 NSColor.red 更浅的红色,因为它的深色遮住了标题。但您可以对此进行试验,直到获得看起来不错的结果。
关于swift - 如何为 NSWindow 的标题栏着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47759424/