【问题标题】:Swift NSTextField, execute on Cmd + EnterSwift NSTextField,在 Cmd + Enter 上执行
【发布时间】:2020-05-14 20:04:00
【问题描述】:

所以,只是一些上下文,我已经为 NSTextView 实现了一个包装 SwiftUI 视图,一切工作或多或少都很好,但我想添加一个监听器,用于按下 Cmd + Enter 组合,到目前为止我得到了这个:

class Coordinator: NSObject, NSTextViewDelegate {
    var parent: NSTextViewWrapper

    init(_ parent: NSTextViewWrapper) {
        self.parent = parent
    }

    func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        if commandSelector == #selector(NSResponder.insertNewLine(_:)) {
            let event = NSApp.currentEvent
            // if event?.modifierFlags != NSEvent.ModifierFlags.command {
            // Here I would like to trigger some action when the user is done editing the text field and wants to commit the result
            //   return true
            // }
                return false
            }
            return false
        }

在我的一生中,我无法弄清楚如何做到这一点。

【问题讨论】:

  • if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == [.command] && event.keyCode == 36 { ... } else { ... }
  • 您介意扩大您的答案吗?看来我不需要覆盖委托上的 textView 函数并只听事件?

标签: swift macos cocoa swiftui


【解决方案1】:

很好。有了@LeoDabus 输入,真的没什么可改变的:

func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    if let event: NSEvent = NSApp.currentEvent {
        if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == [.command] && event.keyCode == 36 {
            print("caught [⌘ + ⏎]")
        }
        return true
    }
    return false
}

因此,用评论部分的一条晦涩的单行词结束了徒劳无功的时间。 ?

【讨论】:

    猜你喜欢
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2022-09-22
    • 1970-01-01
    相关资源
    最近更新 更多