如何以编程方式在macOS上的Swift中添加NSView

如何以编程方式在macOS上的Swift中添加NSView,swift,xcode,macos,cocoa,Swift,Xcode,Macos,Cocoa,尝试以编程方式添加简单NSView 它没有出现 **回答**:Do.wantsLayer=true before.backgroundColor=.black 我将颜色设置为黑色,因此我希望窗口中有一个黑色正方形 我使用的是Xcode 10.2 Swift 5 import Cocoa class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad()

尝试以编程方式添加简单NSView

它没有出现

**回答**:Do.wantsLayer=true before.backgroundColor=.black

我将颜色设置为黑色,因此我希望窗口中有一个黑色正方形

我使用的是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)
    }
}

self.view.addSubView(view)not view addSubView关于此代码为何解决OP问题的解释这对于帮助未来的读者非常重要。请注意,不是我的反对票,但您的代码没有ViewController是没有意义的<代码>self.view实例仅存在于NSViewController方法或计算属性中。在设置图层背景颜色之前,需要将WantLayer设置为true
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)