更改NSView背景颜色的最佳方法

时间:2010-06-03 01:25:26

标签: objective-c macos background-color nsview

我正在寻找更改backgroundColor的{​​{1}}的最佳方法。我还希望能够为NSView设置适当的alpha掩码。类似的东西:

NSView

我注意到myView.backgroundColor = [NSColor colorWithCalibratedRed:0.227f green:0.251f blue:0.337 alpha:0.8]; 有这种方法,我不是NSWindowNSColorWheel背景选项的忠实粉丝,但如果他们是最好的,愿意使用

18 个答案:

答案 0 :(得分:129)

是的,你自己的回答是正确的。您也可以使用Cocoa方法:

- (void)drawRect:(NSRect)dirtyRect {
    // set any NSColor for filling, say white:
    [[NSColor whiteColor] setFill];
    NSRectFill(dirtyRect);
    [super drawRect:dirtyRect];
}

在斯威夫特:

class MyView: NSView {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // #1d161d
        NSColor(red: 0x1d/255, green: 0x16/255, blue: 0x1d/255, alpha: 1).setFill()
        dirtyRect.fill()
    }

}

答案 1 :(得分:111)

一种简单有效的解决方案是将视图配置为使用Core Animation层作为其后备存储。然后,您可以使用-[CALayer setBackgroundColor:]设置图层的背景颜色。

- (void)awakeFromNib {
   self.wantsLayer = YES;  // NSView will create a CALayer automatically
}

- (BOOL)wantsUpdateLayer {
   return YES;  // Tells NSView to call `updateLayer` instead of `drawRect:`
}

- (void)updateLayer {
   self.layer.backgroundColor = [NSColor colorWithCalibratedRed:0.227f 
                                                          green:0.251f 
                                                           blue:0.337 
                                                          alpha:0.8].CGColor;
}

就是这样!

答案 2 :(得分:68)

如果您是故事板爱好者,可以通过以下方式不需要任何代码

NSBox 添加为NSView的子视图,并将NSBox的框架调整为与NSView相同。

在Storyboard或XIB中,将标题位置更改为无,将框类型更改为自定义,将边框类型更改为“无”,将边框颜色更改为您喜欢的任何内容。

以下是截图:

enter image description here

结果如下:

enter image description here

答案 3 :(得分:32)

如果先将“WantsLayer”设置为“YES”,则可以直接操作图层背景。

[self.view setWantsLayer:YES];
[self.view.layer setBackgroundColor:[[NSColor whiteColor] CGColor]];

答案 4 :(得分:26)

想想我是怎么做到的:

- (void)drawRect:(NSRect)dirtyRect {
    // Fill in background Color
    CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
    CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
    CGContextFillRect(context, NSRectToCGRect(dirtyRect));
}

答案 5 :(得分:22)

我经历了所有这些答案,但不幸的是,它们都没有为我工作。但是,经过大约一个小时的搜索,我发现这种非常简单的方式:)

myView.layer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.9);

答案 6 :(得分:20)

编辑/更新: Xcode 8.3.1•Swift 3.1

extension NSView {
    var backgroundColor: NSColor? {
        get {
            guard let color = layer?.backgroundColor else { return nil }
            return NSColor(cgColor: color)
        }
        set {
            wantsLayer = true
            layer?.backgroundColor = newValue?.cgColor
        }
    }
}

用法:

let myView = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
print(myView.backgroundColor ?? "none")     //  NSView's background hasn't been set yet = nil
myView.backgroundColor = .red               // set NSView's background color to red color
print(myView.backgroundColor ?? "none")
view.addSubview(myView)

答案 7 :(得分:7)

最佳解决方案:

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.wantsLayer = YES;
    }
    return self;
}

- (void)awakeFromNib
{
    float r = (rand() % 255) / 255.0f;
    float g = (rand() % 255) / 255.0f;
    float b = (rand() % 255) / 255.0f;

    if(self.layer)
    {
        CGColorRef color = CGColorCreateGenericRGB(r, g, b, 1.0f);
        self.layer.backgroundColor = color;
        CGColorRelease(color);
    }
}

答案 8 :(得分:5)

在斯威夫特:

override func drawRect(dirtyRect: NSRect) {

    NSColor.greenColor().setFill()
    NSRectFill(dirtyRect)

    super.drawRect(dirtyRect)
}

答案 9 :(得分:4)

使用NSBox,它是NSView的子类,允许我们轻松设置样式

Swift 3

let box = NSBox()
box.boxType = .custom
box.fillColor = NSColor.red
box.cornerRadius = 5

答案 10 :(得分:3)

我测试了以下内容,它对我有用(在Swift中):

view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.5).CGColor

答案 11 :(得分:3)

在Swift 3中,您可以创建一个扩展来执行此操作:

extension NSView {
    func setBackgroundColor(_ color: NSColor) {
        wantsLayer = true
        layer?.backgroundColor = color.cgColor
    }
}

// how to use
btn.setBackgroundColor(NSColor.gray)

答案 12 :(得分:2)

毫无疑问,这是最简单的方法,也与Color Set Assets兼容:

快速

view.setValue(NSColor.white, forKey: "backgroundColor")

Objective-C

[view setValue: NSColor.whiteColor forKey: "backgroundColor"];

界面生成器

在界面构建器中添加类型为backgroundColor的用户定义属性NSColor

答案 13 :(得分:2)

只需在图层上设置backgroundColor (在支持视图图层后)。

view.wantsLayer = true
view.layer?.backgroundColor = CGColor.white

答案 14 :(得分:1)

在swift中你可以继承NSView并执行此操作

class MyView:NSView {
    required init?(coder: NSCoder) {
        super.init(coder: coder);

        self.wantsLayer = true;
        self.layer?.backgroundColor = NSColor.redColor().CGColor;
    }
}

答案 15 :(得分:1)

看看RMSkinnedView。您可以在Interface Builder中设置NSView的背景颜色。

答案 16 :(得分:1)

只是小型可重用类(Swift 4.1)

class View: NSView {

   var backgroundColor: NSColor?

   convenience init() {
      self.init(frame: NSRect())
   }

   override func draw(_ dirtyRect: NSRect) {
      if let backgroundColor = backgroundColor {
         backgroundColor.setFill()
         dirtyRect.fill()
      } else {
         super.draw(dirtyRect)
      }
   }
}

// Usage
let view = View()
view.backgroundColor = .white

答案 17 :(得分:0)

这支持在应用程序运行时更改系统范围的外观(打开或关闭暗模式)。如果先将视图的类设置为BackgroundColorView,则还可以在Interface Builder中设置背景颜色。


class BackgroundColorView: NSView {
    @IBInspectable var backgroundColor: NSColor? {
        didSet { needsDisplay = true }
    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        wantsLayer = true
    }

    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        wantsLayer = true
    }

    override var wantsUpdateLayer: Bool { return true }

    override func updateLayer() {
        layer?.backgroundColor = backgroundColor?.cgColor
    }
}