【问题标题】:How to programatically add views to NSWindow (or NSView)?如何以编程方式将视图添加到 NSWindow(或 NSView)?
【发布时间】:2016-07-14 07:54:39
【问题描述】:

我的 ViewController 中有这段代码。但是,我以编程方式添加的视图无处可见。

override func viewDidLoad() {
    super.viewDidLoad()

    let f: NSRect = NSMakeRect(0, 0, 200, 200)
    let v: NSView = NSView(frame: f)
    v.layer?.backgroundColor = NSColor.yellowColor().CGColor
    self.view.addSubview(v)

}

此外,我尝试创建一个自定义 NSWindowController 并将其设置为界面构建器故事板中我的主窗口的自定义类。我有以下代码:

override func windowDidLoad() {
    super.windowDidLoad()

    let f: NSRect = NSMakeRect(0, 0, 200, 200)
    let v: NSView = NSView(frame: f)
    v.layer?.backgroundColor = NSColor.yellowColor().CGColor
    self.window?.contentView?.addSubview(v)

}

这也不起作用:/

我什至尝试将v.wantsLayer = true 设置为我在网上找到的建议的答案之一,但是从一开始这似乎很奇怪,当然什么也没做。

我在这里做错了什么?

【问题讨论】:

  • 你需要设置v.wantsLayer = true
  • 我在两个方法调用viewDidLoad()windowDidLoad() 中再次尝试了v.wantsLayer = true,但是两个视图仍然不可见。我什至尝试了一些疯狂的事情,比如将 contentView 的图层颜色设置为clearColor,认为可能所有视图都添加到它下面。我什至做了self.window?.contentView?.addSubview(v, positioned: NSWindowOrderingMode.Above, relativeTo: self.window?.contentView)... 仍然没有雪茄。视图无处可见。

标签: swift macos nsview nswindow


【解决方案1】:

在我用尽所有可能的情况时回答我自己的问题,当然罪魁祸首最终是wantsLayer

一开始我是这样做的:

override func windowDidLoad() {
    super.windowDidLoad()

    let f: NSRect = NSMakeRect(32, 32, 200, 200)
    let v: NSView = NSView(frame: f)
    v.layer?.backgroundColor = NSColor.greenColor().CGColor
    v.wantsLayer = true
    self.window?.contentView?.addSubview(v)

    if let views = self.window?.contentView?.subviews {
        for v in views {
            print(v.frame)
        }
    }
}

我可以看到视图已添加到 contentView,但是它是不可见的。在意识到自己的错误之前,我做了很多事情:

v.wantsLayer = true 声明需要(当然)位于我指定图层本身的 backgroundColor 的行之上。

所以是的……现在可以了:

override func windowDidLoad() {
    super.windowDidLoad()
    let f: NSRect = NSMakeRect(32, 32, 200, 200)
    let v: NSView = NSView(frame: f)
    v.wantsLayer = true
    v.layer?.backgroundColor = NSColor.greenColor().CGColor
    self.window?.contentView?.addSubview(v)
}

【讨论】:

    猜你喜欢
    • 2012-08-06
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2012-06-26
    • 2017-10-09
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多