Layer-backed NSView subclass causes z-index issue on its non layer-backed superview

744 views Asked by At

I'm trying to understand how layer-backed NSViews work. I have created the following code inside a playground.

import Cocoa
import XCPlayground

class MyView: NSView {

override init(frame: NSRect) {
    super.init(frame: frame)

    wantsLayer = true   //if commented change centerX & centerY accordingly
    layerContentsRedrawPolicy = .OnSetNeedsDisplay
    layer!.backgroundColor = CGColorCreateGenericRGB(0.0, 0.0, 0.0, 0.5)
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
}

}

let containerView: NSView = NSView(frame: CGRectMake(0, 0, 150, 165))
let myView: MyView = MyView(frame: containerView.frame)
let label: NSTextField = NSTextField(frame: NSRect(x: 0.0, y: 0.0, width: 100, height: 22))
label.stringValue = "Please wait..."
label.drawsBackground = false
label.bordered = false
label.selectable = false
label.textColor = NSColor.whiteColor()

//containerView.addSubview(myView)
containerView.addSubview(myView)
containerView.addSubview(label, positioned: .Above, relativeTo: myView)

XCPShowView("view", containerView)

Essentially I've created a layer-backed NSView subclass. Then I'm adding this subclass into the non layer-backed containerView. I'm also adding an NSTextField into containerView, by explicitly positioning it above the layer-backed NSView subclass.

My aim is to have the NSTextField show above the layer-backed view. However, in the assistant editor the NSTextField view appears below the layer-backed view. Could someone please help understand why this happens?

1

There are 1 answers

0
nstein On

After battling with the issue for quite a bit I was able to find out that I had to set

label.wantsLayer = true
label.layerContentsUpdatePolicy = .OnSetNeedsDisplay

for the z-index to be correct. I'm still not sure as to why this is the case, since label isn't part of the MyView view hierarchy but rather part of the broader containerView one, which isn't layer-backed.