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

如何解决macOS全屏窗口中NSCursor无法自动隐藏的问题?

SwiftUI全屏模式下光标自动隐藏失效问题

问题现象

以下代码在窗口模式下可正常隐藏光标,但切换到全屏运行时,光标无法自动隐藏:

import SwiftUI
import Combine

struct ContentView: View {
    @State private var activityTimer: Cancellable?
    @State private var activityCountDownInterval: TimeInterval = 3
    @State private var isActive: Bool = true
    
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .padding()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .onAppear {
            startActivityTimer()
        }
        .onContinuousHover { phase in
            switch phase {
            case .active(_):
                resetActivityTimer()
                isActive = true
            case .ended: ()
            }
        }
        .onChange(of: isActive) { oldValue, newValue in
            if isActive == false {
                NSCursor.setHiddenUntilMouseMoves(true)
            }
        }
    }
    
    private func startActivityTimer() {
        activityTimer?.cancel()
        
        activityTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect().prefix(3).sink { _ in
            if activityCountDownInterval > 1 {
                activityCountDownInterval -= 1
            } else {
                activityCountDownInterval = 3
                activityTimer?.cancel()
                isActive = false
            }
        }
    }
    
    private func resetActivityTimer() {
        activityCountDownInterval = 3
        startActivityTimer()
    }
}

#Preview {
    ContentView()
}

临时解决办法

将文本组件修改为以下形式后,全屏模式下光标即可正常隐藏:

Text("Hello, world! \(isActive)")

原因推测

这种差异推测是布局更新触发机制导致的:修改后的文本会随isActive状态变化重新渲染,强制触发视图刷新,进而让光标隐藏逻辑在全屏环境下生效。

补充说明

使用现代SwiftUI API .pointerVisibility(.hidden) 同样无法解决该问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:42:09