Adit Gupta
Adit Gupta

Reputation: 1334

Changing background color of NSView in Swift 2.0

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.

Upvotes: 3

Views: 2718

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236360

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 {

        }
    }
}

Upvotes: 10

Related Questions