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

时间:2023-01-24 09:04:24

I'm looking for the best way to change the backgroundColor of an NSView. I'd also like to be able to set the appropriate alpha mask for the NSView. Something like:

我正在寻找改变NSView背景颜色的最佳方法。我还想为NSView设置适当的alpha蒙版。喜欢的东西:

myView.backgroundColor = [NSColor colorWithCalibratedRed:0.227f 
                                                   green:0.251f 
                                                    blue:0.337 
                                                   alpha:0.8];

I notice that NSWindow has this method, and I'm not a big fan of the NSColorWheel, or NSImage background options, but if they are the best, willing to use.

我注意到NSWindow有这个方法,我不太喜欢NSColorWheel或NSImage后台选项,但如果它们是最好的,愿意使用。

15 个解决方案

#1


121  

Yeah, your own answer was right. You could also use cocoa methods:

是的,你自己的答案是正确的。您还可以使用cocoa方法:

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

In Swift:

迅速:

class MyView: NSView {

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

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

}

#2


106  

An easy, efficient solution is to configure the view to use a Core Animation layer as its backing store. Then you can use -[CALayer setBackgroundColor:] to set the background color of the layer.

一个简单、有效的解决方案是将视图配置为使用核心动画层作为其支持存储。然后可以使用-[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;
}

That’s it!

就是这样!

#3


49  

If you are a storyboard lover, here is a way that you don't need any line of code.

如果你是一个故事板爱好者,这里有一种你不需要任何代码的方法。

Add NSBox as a subview to NSView and adjust NSBox's frame as the same with NSView.

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

In Storyboard or XIB change Title position to None, Box type to Custom, Border Type to "None", and Border color to whatever you like.

在故事板或XIB中,将标题位置更改为None,框类型更改为Custom,边框类型更改为“None”,边框颜色更改为您喜欢的任何颜色。

Here is a screenshot:

这里是一个截图:

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

This is the result:

这是由于:

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

#4


28  

If you setWantsLayer to YES first, you can directly manipulate the layer background.

如果你先设置为YES,你可以直接操作图层背景。

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

#5


26  

Think I figured out how to do it:

我想我知道怎么做了:

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

#6


21  

I went through all of these answers and none of them worked for me unfortunately. However, I found this extremely simple way, after about an hour of searching : )

我经历了所有这些答案,但不幸的是,没有一个是我的。然而,在经过了一个小时的搜索之后,我发现了这个非常简单的方法。

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

#7


19  

edit/update: Xcode 8.3.1 • Swift 3.1

编辑/更新: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
        }
    }
}

usage:

用法:

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)

#8


7  

Best Solution :

最好的解决办法:

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

#9


5  

In Swift:

迅速:

override func drawRect(dirtyRect: NSRect) {

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

    super.drawRect(dirtyRect)
}

#10


3  

I tested the following and it worked for me (in Swift):

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

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

#11


3  

In Swift 3, you can create an extension to do it:

在Swift 3中,您可以创建一个扩展来完成:

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

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

#12


3  

Use NSBox, which is a subclass of NSView, allowing us to easily style

使用NSBox,它是NSView的一个子类,允许我们很容易地设计样式

Swift 3

斯威夫特3

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

#13


1  

Have a look at RMSkinnedView. You can set the NSView's background color from within Interface Builder.

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

#14


1  

In swift you can subclass NSView and do this

在swift中,您可以子类化NSView并执行此操作

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

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

#15


1  

Just small reusable class (Swift 4.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

#1


121  

Yeah, your own answer was right. You could also use cocoa methods:

是的,你自己的答案是正确的。您还可以使用cocoa方法:

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

In Swift:

迅速:

class MyView: NSView {

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

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

}

#2


106  

An easy, efficient solution is to configure the view to use a Core Animation layer as its backing store. Then you can use -[CALayer setBackgroundColor:] to set the background color of the layer.

一个简单、有效的解决方案是将视图配置为使用核心动画层作为其支持存储。然后可以使用-[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;
}

That’s it!

就是这样!

#3


49  

If you are a storyboard lover, here is a way that you don't need any line of code.

如果你是一个故事板爱好者,这里有一种你不需要任何代码的方法。

Add NSBox as a subview to NSView and adjust NSBox's frame as the same with NSView.

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

In Storyboard or XIB change Title position to None, Box type to Custom, Border Type to "None", and Border color to whatever you like.

在故事板或XIB中,将标题位置更改为None,框类型更改为Custom,边框类型更改为“None”,边框颜色更改为您喜欢的任何颜色。

Here is a screenshot:

这里是一个截图:

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

This is the result:

这是由于:

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

#4


28  

If you setWantsLayer to YES first, you can directly manipulate the layer background.

如果你先设置为YES,你可以直接操作图层背景。

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

#5


26  

Think I figured out how to do it:

我想我知道怎么做了:

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

#6


21  

I went through all of these answers and none of them worked for me unfortunately. However, I found this extremely simple way, after about an hour of searching : )

我经历了所有这些答案,但不幸的是,没有一个是我的。然而,在经过了一个小时的搜索之后,我发现了这个非常简单的方法。

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

#7


19  

edit/update: Xcode 8.3.1 • Swift 3.1

编辑/更新: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
        }
    }
}

usage:

用法:

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)

#8


7  

Best Solution :

最好的解决办法:

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

#9


5  

In Swift:

迅速:

override func drawRect(dirtyRect: NSRect) {

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

    super.drawRect(dirtyRect)
}

#10


3  

I tested the following and it worked for me (in Swift):

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

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

#11


3  

In Swift 3, you can create an extension to do it:

在Swift 3中,您可以创建一个扩展来完成:

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

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

#12


3  

Use NSBox, which is a subclass of NSView, allowing us to easily style

使用NSBox,它是NSView的一个子类,允许我们很容易地设计样式

Swift 3

斯威夫特3

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

#13


1  

Have a look at RMSkinnedView. You can set the NSView's background color from within Interface Builder.

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

#14


1  

In swift you can subclass NSView and do this

在swift中,您可以子类化NSView并执行此操作

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

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

#15


1  

Just small reusable class (Swift 4.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