Search code examples
xcodecocoacalayernsviewcgrect

Drawing a colored rectangle in a macOS app (Swift)


Just started to learn Swift. I’ve created a macOS app project using the Xcode 6 Beta 6. Now I want to use the ViewController.swift to draw a colored rectangle (for testing purposes) in the apps main view (a NSWindow within the Main.storyboard).

I’ve tried this:

override func viewDidLoad() {
   let myRect = NSView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
   myRect!.backgroundColor = NSColor.redColor().CGColor // app crashes here
   self.view.addSubview(myRect)
}

The app crashed in the third line: EXC_BAD_INSTRUCTION.

Not only Swift but also Xcode is totally new to me and I would appreciate any help.


Solution

  • It’s been a while since I asked this question but I noticed that it got a lot of views recently, so providing an actual answer (Swift 4.2) might be helpful for a bunch of people:

    override func viewDidLoad() {
       let myFrame = NSRect(x: 0.0, y: 0.0, width: 200.0, height: 200.0)
       let myRect = NSView(frame: myFrame)
       myRect.backgroundColor = NSColor.red
       self.view.addSubview(myRect)
    }