【问题标题】:How do I programmatically add an NSView in Swift on macOS [duplicate]如何在 macOS 上以编程方式在 Swift 中添加 NSView [重复]
【发布时间】:2019-04-19 11:41:23
【问题描述】:

尝试以编程方式添加一个简单的 NSView。

它没有出现。

** 答案**:在 .backgroundColor = .black 之前做 .wantsLayer = true

我将颜色设置为黑色,所以我希望窗口中有一个黑色方块。

我正在使用 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)
    }
}

【问题讨论】:

  • 在设置图层backgroundColor之前需要先设置wantsLayer为true

标签: swift xcode macos cocoa


【解决方案1】:
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)

【讨论】:

  • self.view.addSubView(view) not view addSubView
  • 解释为什么这段代码可以解决 OP 问题,这对于帮助未来的读者很重要
  • 顺便说一句,这不是我的反对意见,但没有 ViewController 的代码毫无意义。 self.view 实例仅存在于 NSViewController 方法或计算属性中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
相关资源
最近更新 更多