SwiftUI监听键盘事件
SwiftUI中的TextEditor没有类似于TextField的onCommit()或onSubmit()方法,所以无法直接使用Enter键做出此动作。
下面是一个变通方法,使用NSEvent监听实现Enter提交,Enter+Option换行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import SwiftUI
struct TestView: View { @State private var text = "" var body: some View { TextEditor(text: $text)
.onChange(of: message.messages.count, perform: { _ in text = "" DispatchQueue.main.asyncAfter(deadline: .now() + 0.001) { NSApplication.shared.sendAction(#selector(NSText.deleteBackward(_:)), to: nil, from: nil) } }) .font(.title2) .padding(5) .focused($isFocused) .frame(minHeight: 15, maxHeight: 180) .fixedSize(horizontal: false, vertical: true) .scrollContentBackground(.hidden) .overlay( RoundedRectangle(cornerRadius: 15) .stroke(isFocused == true ? Color.blue : Color.secondary, lineWidth: isFocused == true ? 2 : 0.3) )
.onAppear { NSEvent.addLocalMonitorForEvents(matching: [.keyDown]) { nsevent in if nsevent.keyCode == 36 && !nsevent.modifierFlags.contains(.option) { if text.last != nil { if !text.isEmpty, !text.allSatisfy({ $0.isNewline }) { print("Enter提交") } } } return nsevent } } } }
|