You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 15:50:17