3

I am trying to change the background color of NSView and have tried one of the solution outlined in this answer. However, it's not working for me. What am I missing here? Should I use viewWillAppear() here or it only meant for iOS?

Related code:

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.wantsLayer = true

    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    override func awakeFromNib() {
        if self.view.layer != nil {
            let color : CGColorRef = CGColorCreateGenericRGB(1.0, 0, 0, 1.0)
            self.view.layer?.backgroundColor = color
        }

    }
}

P.S - I'm new to OS X/iOS programming and trying to figure my way out through documentation and existing solutions. Using Xcode 7 beta 4.

Community
  • 1
  • 1
Adit Gupta
  • 1,314
  • 1
  • 18
  • 32

1 Answers1

10
import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor(red: 1, green: 0, blue: 0, alpha: 1).CGColor

    }

    override var representedObject: AnyObject? {
        didSet {

        }
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    view.wantsLayer = true is the crucial point here. Seems starting some point CALayer is not automatically allocated for the view. Don't remember when it was introduced – Alfishe May 21 '17 at 01:43
  • another option is to change the window background color inside viewWillAppear – Leo Dabus May 21 '17 at 01:45