从NSWindowController以编程方式呈现视图控制器

时间:2017-09-08 11:30:26

标签: swift macos cocoa nswindowcontroller

我正在使用swift 4 for macOS,我可以使用以下代码以编程方式显示另一个视图控制器:

@IBAction func showVC(_ sender: NSButton) {
    let vc = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil).instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "MyVC")) as! NSViewController
    self.presentViewController(vc, asPopoverRelativeTo: sender.bounds, of: sender, preferredEdge: .maxX, behavior: .transient)
}

现在我想从NSWindowController做同样的事情,但我得到“错误”:

value of type 'WindowController' has no member 'presentViewController'

还有其他方法可以实现吗?

下次尝试

   @IBAction func showVC(_ sender: NSToolbarItem) {
    let vc = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil).instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "MyVC")) as! NSViewController
self.contentViewController?.presentViewController(x, asPopoverRelativeTo: sender.view!.bounds, of: sender.view!, preferredEdge: .maxX, behavior: .transient)

    }        

应用程序在第二行崩溃:

fatal error: unexpectedly found nil while unwrapping an Optional value

我检查以下内容:

print(sender.view?.bounds ?? "No bounds")
print(sender.view ?? "No view")

打印结果

No bounds
No view

但为什么??

1 个答案:

答案 0 :(得分:1)

尝试:

let storyBoard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
let mainViewController : NSViewController = storyBoard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "myVC")) as! NSViewController
self.contentViewController!.presentViewController(mainViewController, asPopoverRelativeTo: sender.bounds, of: sender, preferredEdge: .maxY, behavior: .transient)