You need to enable JavaScript to run this app. Swift中如何实现NSWindow切换桌面空间时始终悬浮固定
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何实现NSWindow切换桌面空间时始终悬浮固定

解决方案

你只需要调整window.level和collectionBehavior两个配置项即可实现需求,核心是去掉错误的.stationary属性、补充.transient属性,同时把窗口层级调整为系统通知对应的层级:

具体修改点

  • 移除collectionBehavior中的.stationary配置,该属性会导致窗口跟随桌面空间移动
  • 给collectionBehavior新增.ignoresCycle、.transient配置,.transient是实现空间切换时窗口固定不滑动的核心属性
  • 将窗口层级从.floating调整为系统通知对应的层级,确保窗口始终在最上层显示
  • 可选:将makeKeyAndOrderFront替换为orderFront,避免窗口抢走当前应用的输入焦点

修改后完整代码

let window = NSWindow(contentRect: NSRect(x: 300, y: 300, width: 200, height: 200), styleMask: [.borderless], backing: .buffered, defer: true)
window.backgroundColor = NSColor.green
// 调整为系统通知对应的窗口层级
window.level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.notificationWindowLevelKey)))

// 修正collectionBehavior配置
window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .ignoresCycle, .transient]
// 不需要焦点就用orderFront,需要焦点可以保留原来的makeKeyAndOrderFront
window.orderFront(nil)

内容的提问来源于stack exchange,提问作者unknown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:00:00