Dmitri K. Dmitri K. - 1 year ago 250
Swift Question

NSView background layer

Can;t figure out the answer yet, but I have this code which is called for a view:

func gradient(fillView view: NSView, withGradientFromColors colors: Array<NSColor>) {

let gradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds

let color1 = colors[0].cgColor
let color2 = colors[1].cgColor
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [0.0, 1.0]


This code takes two values of NSColor and should create a gradient background.

The code works! Buut, if i try to execute something else on this view for example i have a label on top of it which needs to be shown, it's actually not shown after this code is executed. I believe it is somehow behind the view that i draw?

Any fast way of resolving this issue?

Answer Source

Change the adding of sublayer as below:

view.layer?.insertSublayer(gradientLayer, at: 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download