我正在使用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中执行同样的操作,但下面是“error”:
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
但为什么呢??
最佳答案
试试这个:
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)
关于swift - 从NSWindowController以编程方式显示 View Controller ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46115505/