macos - SwiftUI:如何在 macOS 应用程序启动后运行代码
问题描述
我想NSEvent.addGlobalMonitorForEvents
在我的应用程序完成启动时使用,以便为其添加全局键盘快捷键。
首先,我尝试在init
函数中编写一些代码,但它只在我使用时有效,在我使用时NSEvent.EventTypeMask.leftMouseDown
似乎不起作用NSEvent.EventTypeMask.keyDown
。
import SwiftUI
@main
struct GameFakeTouchApp: App {
var body: some Scene {
WindowGroup {
// ...
}
}
init() {
// Works, but the Scene doesn't show correctly.
NSEvent.addGlobalMonitorForEvents(
matching: NSEvent.EventTypeMask.leftMouseDown,
handler: { /* ... */ })
// Doesn't work at all.
NSEvent.addGlobalMonitorForEvents(
matching: NSEvent.EventTypeMask.keyDown,
handler: { /* ... */ })
}
}
我还尝试添加一个main
函数而不是内置函数。但是,应用程序在完成启动后立即终止。
谁能告诉我我做错了什么以及为什么我的代码不起作用?
我正在使用 Xcode 12、Swift 5 和 macOS Big Sur 11.5.2。
解决方案
推荐阅读
- c++ - pow 在 CUDA 的 __device__ 函数中无法正常工作
- javascript - 我为什么要关心在浏览器中取消 ajax 请求?
- r - 根据上下文绘制数据可视化图
- android - 如何处理flutter_bluetooth_serial包中的String数据?
- mysql - MacOS MySQL_8的where子句中TINYINT UNSIGNED数据列不能减
- c++ - 删除数组时“free():在 tcache 2 中检测到双重空闲”
- python - 如何为 Django 项目中的帖子创建评论模型
- ruby-on-rails - 折叠的导航栏没有在 Rails 应用程序中使用 Bootstrap 扩展
- reactjs - 可重用组件原因警告:无法从不同组件的函数体内更新组件
- node.js - mongoose populate() 不适用于 find()