开发AutoClicker时遇‘CGEvent’未找到错误,请问原因是什么?
解决‘CGEvent’未找到的错误
错误原因
- 平台不匹配:
CGEvent是macOS专属的CoreGraphics API,iOS、iPadOS、WatchOS等平台并未提供这个类。如果你的项目目标平台不是macOS,就会触发找不到的编译错误。 - 极端情况可能是SDK版本过低,但该概率极低,
CGEvent在较早的macOS SDK版本中就已存在。
修复方案
确认项目目标平台:
打开Xcode项目设置,检查“Deployment Info”区域,确保目标平台设置为macOS。跨平台项目添加条件编译:
若项目需要支持多平台,用平台条件编译包裹CGEvent相关代码:import SwiftUI import CoreGraphics #if os(macOS) func click(x: Int, y: Int) { let mouseDown = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: CGPoint(x: x, y: y), mouseButton: .left) let mouseUp = CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: CGPoint(x: x, y: y), mouseButton: .left) mouseDown?.post(tap: .cghidEventTap) mouseUp?.post(tap: .cghidEventTap) } #endifmacOS运行时权限补充:
编译通过后,macOS会限制应用模拟输入事件,需前往「系统偏好设置→安全性与隐私→辅助功能」,勾选授权你的应用,否则点击事件无法生效。
内容的提问来源于stack exchange,提问作者developer
相关产品推荐
相关产品推荐

