3

Trying to add a simple NSView programmatically.

It does not appear.

** ANSWER **: Do .wantsLayer = true before .backgroundColor = .black

I set the color to black so I expect there to be a black square in the window.

I am using Xcode 10.2 Swift 5

import Cocoa

class ViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let newView = NSView(frame: NSRect(x: 10,y: 10, width: 100,height: 100))
        newView.layer?.backgroundColor = .black
        newView.wantsLayer = true
        self.view.addSubview(newView)
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

6
import Cocoa

let frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
let view = NSView(frame: frame)

view.wantsLayer = true
view.layer?.backgroundColor = NSColor.black.cgColor
self.view.addSubView(view)