Swift macOS App非模态显示新增NSViewController失败,求示例代码
在Swift macOS App中非模态显示NSViewController的正确方法
你之前的代码无法显示新窗口的核心原因是:刚从Storyboard实例化的NewViewController的view还未绑定到任何NSWindow,newView.view.window返回的是nil,导致NSWindowController没有可加载的有效窗口。
以下是修正后的示例代码,可实现非模态显示新的NSViewController:
@IBAction func click(_ sender: Any) { // 安全地从Storyboard实例化目标ViewController guard let newViewController = storyboard?.instantiateController(withIdentifier: "NewView") as? NewViewController else { return } // 创建新窗口,定义初始尺寸和窗口样式 let newWindow = NSWindow( contentRect: NSRect(x: 200, y: 200, width: 400, height: 300), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false ) // 将新ViewController设置为窗口的内容控制器 newWindow.contentViewController = newViewController // 可选:让窗口在屏幕居中显示 newWindow.center() // 通过窗口控制器显示窗口 let windowController = NSWindowController(window: newWindow) windowController.showWindow(nil) }
额外注意事项
- 确保
NewViewController在Storyboard中的Storyboard ID确实设置为NewView,否则会出现实例化失败的情况。 - 这种方式创建的窗口是非模态的,用户可以同时与原窗口和新窗口交互。
内容的提问来源于stack exchange,提问作者marky1
相关产品推荐
相关产品推荐

