Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift + NSViewController background color (Mac App)

Tags:

I am trying to change the background color of my View. The View Controller class is NSViewController type.

How this can be done? In iOS UIKit (UIViewController) there is self.view.backgroundColor, but NSViewController doesn't have that.

And second problem is how can I change the color of the applications Title Bar? I think the background color doesn't affect to that.

Mac application, language Swift. XCode 6.1.

like image 453
Rohirm Avatar asked Oct 24 '14 17:10

Rohirm


2 Answers

I managed to change background color of main view. NSViewController does not have backgroundColor property indeed, so I used the layer property of NSView that belongs to NSViewController. Here is the 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         }      } } 

It will initialize the view controller with red background.

For Title Bar color, I created NSWindowController and assinged it to main window controller from storyboard. Here is the code.

class MainWindow: NSWindowController {      override func windowDidLoad() {         super.windowDidLoad()          super.window?.backgroundColor = NSColor(calibratedRed: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)     }  } 

I hope this will help.

like image 79
cyt Avatar answered Sep 17 '22 15:09

cyt


Careful: calling setLayer: or setWantsLayer: breaks any WebViews you might have in your application in very creative ways! (Even in different windows...)

Please see this answer here Best way to change the background color for an NSView.

like image 35
JZAU Avatar answered Sep 17 '22 15:09

JZAU