Search code examples
objective-ccocoaswiftcalayernsview

How to set the background of a CALayer to be transparent without affecting the borders?


I have a layer-backed NSView in my Cocoa application. Using the following code the entire custom view is made transparent:

    self.layer?.opaque = false
    self.layer?.opacity = 0

Unfortunately, I need the border of the CALayer to remain visible (and currently it is being made transparent). How best do I go about getting only the border to show?

EDIT

I have now managed to get it working but I am unsure as to why.

I didn't think it was relevant previously but The layer backed NSView is actually an NSTextField. This exposes a backgroundColor field that seems to "have more influence" than that of the CALayer

setting self.backgroundColor = NSColor.clearColor() has done the job.

However, I have opted into layers by

  1. Setting self.wantsLayer = true
  2. Overriding wantsUpdateLayer and returning true
  3. The code manipulating the layers was in my updateLayer() method

The question now is why the above works and NOT using clearColor on the CALayer?


Solution

  • FINDINGS

    The fact that it is a layer-backed NSTextField as opposed to a regular layer-backed NSView appears to be important... it has its own background that will appear in front of the layer's background unless you set the following:

    self.drawsBackground = false
    

    If you do that, then you can indeed use the NSColor.clearColor().CGColor as the layer's backgroundColor.

    If you don't, then it looks like you need to set the backgroundColor of your view directly to control the background.