Showing posts with label swift. Show all posts
Showing posts with label swift. Show all posts

Tuesday, September 8, 2015

How to change the background color of an NSView loaded from nib/xib in Swift

I have an NSWindow and in the UI designer I have set its top-level view to be a custom NSView type I created (class Canvas : NSView).




This worked for me in xcode 7/swift 2.0. In order to set its background color in code you need to override NSView's awakeFromNib() function as such:

import Cocoa

class Canvas : NSView {
    
    override func awakeFromNib() {
        self.layer?.backgroundColor = NSColor(calibratedRed: 1, green: 1, blue: 1, alpha: 1).CGColor //set background to white ( not sure if it should be called before parent func)
        super.awakeFromNib()
    }
}

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    
    @IBOutlet weak var canvas: Canvas!
    @IBOutlet weak var window: NSWindow!
    
    func applicationDidFinishLaunching(aNotification: NSNotification) {
    }
    
    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }
    
}