MacOS App无法将SwiftUI视图设为根视图控制器,窗口无内容如何解决
根因分析
- 你实例化
NSWindowController后没有调用showWindow()方法触发窗口渲染 - 没有将
NSWindowController实例声明为AppDelegate的成员变量持有,函数执行结束后实例会被ARC自动释放,窗口自然无法展示
修复方案
直接修改你的AppDelegate代码即可,ContentView无需调整:
class AppDelegate: NSObject, NSApplicationDelegate { // 声明为成员变量持有,避免被自动释放 var mainWindowController: NSWindowController? let contentView = NSHostingController(rootView: ContentView()) func applicationDidFinishLaunching(_ aNotification: Notification) { let storyBoard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: Bundle.main) mainWindowController = storyBoard.instantiateController(withIdentifier: "Main Window") as? NSWindowController guard let mainWindowController = mainWindowController else { return } mainWindowController.contentViewController = contentView // 调用方法展示窗口 mainWindowController.showWindow(nil) } }
可选纯代码实现(无需依赖Storyboard)
如果你不想维护Storyboard配置,可以直接用代码初始化窗口,实现更简洁:
class AppDelegate: NSObject, NSApplicationDelegate { var mainWindow: NSWindow? func applicationDidFinishLaunching(_ aNotification: Notification) { // 直接创建窗口实例 mainWindow = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false ) mainWindow?.center() // 直接设置SwiftUI视图为窗口内容 mainWindow?.contentView = NSHostingView(rootView: ContentView()) mainWindow?.makeKeyAndOrderFront(nil) } }
内容的提问来源于stack exchange,提问作者user4150758
相关产品推荐
相关产品推荐

