簡體   English   中英

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

[英]Best way to change the background color for an NSView

我正在尋找更改NSViewbackgroundColor的最佳方法。 我還希望能夠為NSView設置適當的alpha掩碼。 就像是:

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

我注意到NSWindow有這個方法,我不是NSColorWheelNSImage背景選項的NSColorWheel粉絲,但如果它們是最好的,願意使用。

是的,你自己的回答是對的。 您還可以使用 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()
    }

}

一個簡單有效的解決方案是配置視圖以使用核心動畫層作為其后備存儲。 然后你可以使用-[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;
}

就是這樣!

如果您是故事板愛好者,這里有一種您不需要任何代碼行的方法

NSBox作為子視圖添加到 NSView 並像 NSView 一樣調整 NSBox 的框架。

在 Storyboard 或 XIB 中,將 Title position 更改為 None,將 Box type 更改為Custom ,將 Border Type 更改為“None”,將邊框顏色更改為您喜歡的任何顏色。

這是一個屏幕截圖:

在此處輸入圖片說明

這是結果:

在此處輸入圖片說明

如果先將WantsLayer設置為YES,就可以直接操作圖層背景。

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

想我想出了如何做到這一點:

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

我經歷了所有這些答案,但不幸的是,沒有一個對我有用。 但是,經過大約一個小時的搜索,我發現了這種非常簡單的方法:)

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

編輯/更新: 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)

最佳解決方案:

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

在斯威夫特:

override func drawRect(dirtyRect: NSRect) {

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

    super.drawRect(dirtyRect)
}

使用 NSBox,它是 NSView 的子類,讓我們可以輕松地設置樣式

斯威夫特 3

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

只需在圖層上設置backgroundColor (在支持視圖圖層之后)。

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

我測試了以下內容,它對我有用(在 Swift 中):

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

毫無疑問,最簡單的方法,也與顏色集資產兼容:

斯威夫特

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

目標-C

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

界面生成器

在界面構建器中添加用戶定義的屬性backgroundColor ,類型為NSColor

在 Swift 3 中,你可以創建一個擴展來做到這一點:

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

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

在 swift 中,您可以繼承 NSView 並執行此操作

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

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

這支持在應用程序運行時更改系統范圍的外觀(打開或關閉暗模式)。 如果您先將視圖的類設置為 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
    }
}

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

只是小的可重用類(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM