swift - MacOS Playground : How can change the background color?

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

但是 View 并没有改变颜色:

enter image description here

还有“Hello world”标签是从哪里来的?

非常感谢你的帮助

最佳答案

您只需要将 View 的 wantsLayer 属性设置为 true

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

enter image description here

关于swift - MacOS Playground : How can change the background color?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55600853/

相关文章:

ios - TableView 没有出现在我的容器中

swift - 使用 Reactive Swift 将 View 模型与 View 绑定(bind)

ios - UITableView 不填充 UITabBarController 内的自定义单元格

xcode - locationManager didFailWithError null phonegap 模拟器

ios - 如果 iPhone 没有越狱,macOS 上的 iTunes 可以检测到 iPhone 吗?

ios - 如何将标签栏添加到表格 View 而不是详细 View

objective-c - 如何在 Xcode 中添加 Watch 或 Inspect?

ios - 当音频设备添加到 AVCaptureSession 时,UIImpactFeedbackGenerator 不工作

c++ - 限制文件夹重命名 cocoa

javascript - 如何从 javascript 上的 getUserMedia() 获取超过 3 声道的音频输入