如何让无边框Window在启动后成为Key Window?
解决无边框SwiftUI窗口无法成为Key Window的问题
问题根源
你的代码存在几个关键问题导致窗口无法成为Key Window:
- 初始化
NSWindow时未指定初始尺寸,系统无法识别窗口的可交互区域 - 仅设置
.fullSizeContentView不足以实现无边框无标题效果,需配合.borderless样式 - 无边框窗口默认可能不允许成为Key Window,需显式配置相关属性
修复后的完整代码
import Cocoa import SwiftUI class AppDelegate: NSObject, NSApplicationDelegate { private lazy var window: NSWindow = { // 初始化时指定窗口初始尺寸,可根据需求调整 let contentRect = NSRect(x: 0, y: 0, width: 800, height: 600) let window = NSWindow( contentRect: contentRect, styleMask: [.borderless, .fullSizeContentView], backing: .buffered, defer: false ) // 配置窗口属性以支持Key Window window.isOpaque = false window.hasShadow = true window.isReleasedWhenClosed = false return window }() func applicationDidFinishLaunching(_ aNotification: Notification) { window.contentView = NSHostingView(rootView: ContentView()) window.center() window.setFrameAutosaveName("Main Window") window.isMovableByWindowBackground = true // 激活应用并将窗口设为Key Window NSApp.activate(ignoringOtherApps: true) window.makeKeyAndOrderFront(nil) } } let nsApplication = NSApplication.shared let appDelegate = AppDelegate() nsApplication.delegate = appDelegate // 设置应用激活策略为常规,确保能正常获取焦点 nsApplication.setActivationPolicy(.regular) nsApplication.run()
核心修复说明
- 窗口初始化配置:显式指定
contentRect和正确的styleMask组合(.borderless+.fullSizeContentView),这是无边框窗口的基础配置 - Key Window权限:设置
isOpaque = false,配合无边框样式确保窗口能接收键盘事件 - 应用激活:调用
NSApp.activate(ignoringOtherApps: true),确保应用本身被激活,窗口才能成为Key Window - 激活策略设置:配置
setActivationPolicy(.regular),避免应用在后台运行无法获取焦点
修复后启动应用,窗口会自动成为Key Window,可正常接收键盘输入和鼠标交互,匹配你的预期效果。
内容的提问来源于stack exchange,提问作者swiftPunk
相关产品推荐
相关产品推荐

