6

0129 - SwiftUI for macOS 监听键盘整件的几种方式

 7 months ago
source link: https://atjason.com/daily/2024-01-29.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

0129 - SwiftUI for macOS 监听键盘整件的几种方式

2024-01-29

| 每天写一点

  1. View.onKeyPress. 理论上,这是最合适的。但实际用下来,发现并不能识别比如 upArrow/downArrow 这些特殊的 Key. 虽然看起来可以在代码中指定这些 KeyEquivalent,但实际上并不工作。

  2. View.onAppear { NSEvent.addLocalMonitorForEvents }. 这个方法的问题是,如果多个 View 同时保活,则会被调用多次。如果使用类似单例的方式,又会丢失唤醒整件的上下文信息。

  3. Button.keyboardShortcut. 创建一个 Button 并隐藏起来,同时支持快捷键唤醒。目前来看,这是最能支持 View 级快捷键的方式。但使用隐藏 View 的方式不优雅。且如果是 List 中每个 View 都增加一堆 Button 来实现一系列快捷键,想想也是很浪费资源的做法。并且,隐藏后 .delete 就不能响应了,目前不知道其他快捷键是否有类似的问题。

  4. 通过 Commands menu 中的快捷键,本质还是 Button 的快捷键。但这失去了上下文关联,需要再通过 Context 之类的方法中转信息。

哎,目前还没找到最合适的方式。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK