MacOS Playground: How can change the background co

2020-05-01 07:32发布

问题:

I'm trying to change the background color of main view:

import AppKit
import PlaygroundSupport

class ViewController : NSViewController {
    override func loadView() {
        let nibFile = NSNib.Name("MyView")
        var topLevelObjects : NSArray?
        Bundle.main.loadNibNamed(
            nibFile, owner:nil, topLevelObjects: &topLevelObjects)
        let views = (topLevelObjects as! Array<Any>).filter { $0 is NSView }
        self.view = views[0] as! NSView
        self.view.layer?.backgroundColor = NSColor.white.cgColor
    }
}

PlaygroundPage.current.liveView = ViewController()

But the view doesn't change the color:

Also where the "Hello world" label is coming from?

I'll really appreciate your help

回答1:

You just need to set your view wantsLayer property to true

let view = views[0] as! NSView
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.blue.cgColor