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

Bad*_*ate 142 macos objective-c background-color nsview

我在寻找改变的最佳途径backgroundColorNSView.我也希望能够设置适当的alpha面具NSView.就像是:

myView.backgroundColor = [NSColor colorWithCalibratedRed:0.227f 
                                                   green:0.251f 
                                                    blue:0.337 
                                                   alpha:0.8];
Run Code Online (Sandbox Code Playgroud)

我注意到NSWindow有这种方法,我不是这个NSColorWheelNSImage背景选项的忠实粉丝,但如果他们是最好的,愿意使用.

moh*_*enr 131

是的,你自己的答案是对的.您还可以使用Cocoa方法:

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

在Swift中:

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

}
Run Code Online (Sandbox Code Playgroud)

  • `NSRectFill`使用`NSCompositeCopy`进行填充,因此它会破坏它背后的任何东西 - 它不会在任何祖先视图之上复合.对于具有部分(或完全)透明色的填充,请使用"NSRectFillUsingOperation"http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Miscellaneous/AppKit_Functions/Reference/reference.html# //使用`NSCompositeSourceOver`操作的apple_ref/c/func/NSRectFillUsingOperation. (17认同)

lor*_*isi 113

一种简单有效的解决方案是将视图配置为使用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;
}
Run Code Online (Sandbox Code Playgroud)

而已!

  • 小心:调用`setLayer:`或`setWantsLayer:`以非常有创意的方式打破你在应用程序中可能拥有的任何WebView!(即使在不同的窗口......) (5认同)

JZA*_*ZAU 73

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

NSBox作为子视图添加到NSView并调整NSBox的框架与NSView相同.

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

这是一个截图:

在此输入图像描述

这是结果:

在此输入图像描述

  • 这是一个非常简单的解决方案,应该在文档中 (3认同)

Gab*_*iel 32

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

[self.view setWantsLayer:YES];
[self.view.layer setBackgroundColor:[[NSColor whiteColor] CGColor]];
Run Code Online (Sandbox Code Playgroud)


Bad*_*ate 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));
}
Run Code Online (Sandbox Code Playgroud)

  • 当构建64位或iOS或构建32位像64位时,NSRect只是说CGRect的另一种方式.但是,如果不是,这些都是独立的结构,即使它们可能由相同的成员组成,它们也永远不会被"免费桥接",因为这个术语仅指对象(具有"isa"指针的结构)并使用指针传递,但不是通用结构. (5认同)

gre*_*use 22

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

myView.layer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.9);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,NSView并不总是有一个图层,在这种情况下,它什么都不做.见Ioretoparisi的回答. (7认同)
  • 我花了很多时间尝试在我的控制器的viewDidLoad方法中执行此代码(对于self.myCustomView).我想你应该使用viewWillAppear方法. (3认同)

Leo*_*bus 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

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)
Run Code Online (Sandbox Code Playgroud)


Nag*_*raj 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


onm*_*133 6

使用 NSBox,它是 NSView 的子类,让我们可以轻松地设置样式

斯威夫特 3

let box = NSBox()
box.boxType = .custom
box.fillColor = NSColor.red
box.cornerRadius = 5
Run Code Online (Sandbox Code Playgroud)


Ely*_*Ely 6

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

斯威夫特

view.setValue(NSColor.white, forKey: "backgroundColor")
Run Code Online (Sandbox Code Playgroud)

目标-C

[view setValue: NSColor.whiteColor forKey: "backgroundColor"];
Run Code Online (Sandbox Code Playgroud)

界面生成器

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


Ger*_*eri 6

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

view.wantsLayer = true
view.layer?.backgroundColor = CGColor.white
Run Code Online (Sandbox Code Playgroud)


Ixx*_*Ixx 5

在Swift中:

override func drawRect(dirtyRect: NSRect) {

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

    super.drawRect(dirtyRect)
}
Run Code Online (Sandbox Code Playgroud)


Tyl*_*ong 5

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

view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blackColor().colorWithAlphaComponent(0.5).CGColor
Run Code Online (Sandbox Code Playgroud)