MacOS Playground:如何更改背景颜色?

时间:2019-04-09 20:29:28

标签: swift xcode macos swift-playground

我正在尝试更改主视图的背景颜色:

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()

但是视图不会改变颜色:

enter image description here

“ Hello world”标签也来自哪里?

非常感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您只需要将视图的wantLayer属性设置为true

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

enter image description here