在通过 NSViewRepresentable 嵌入的 NSTextView 中处理键盘输入?(SwiftUI/MacO



我是 SwiftUI 的新手,非常困惑。我设法将NSTextView嵌入到我的SwiftUI视图中,并将其文本与以下代码绑定。

我不明白的是;有没有办法处理NSTextView的键盘输入并相应地更改其文本(例如CMD + R将所选文本的文本颜色设置为红色(?有没有办法在 SwiftUI 中与 UI-Elements 进行交互?

"富文本字段">

struct RichTextField: NSViewRepresentable {
typealias NSViewType = NSTextView

@Binding var attributedString: NSAttributedString 
func makeNSView(context: Context) -> NSTextView {...
// [...]
}

视图

struct EditWindow: View {

@ObservedObject var model: EditEntryViewModel
@Binding var isPresented: Bool

var body: some View {    
RichTextField(attributedString: self.$model.answer1, isEditable: true)
// [...]
}
}

此外,我已经设法在应用程序代表中设置了一个菜单命令,但是我如何使用它来更改任意视图的NSTextView中的文本(在某个位置(?

@IBAction func setTagImportant(_ sender: Any) {
print("setTagImportant")
}

非常感谢您为我阐明了这一点...

具有讽刺意味的是,在最终发布这个问题后,我立即找到了一个解决方案;只需对NSTextView进行子类化,然后覆盖keyDown:

import SwiftUI
class RichTextFieldExtended: NSTextView {

override func keyDown(with event: NSEvent) {

if event.modifierFlags.contains(NSEvent.ModifierFlags.command) {

switch event.keyCode {

case 18: // 1

print("1 PRESSED")                

default:
print("keyCode (event.keyCode) wasn't handled")
super.keyDown(with: event)
}

} else {
super.keyDown(with: event)
}

}

}

然后将子类化的 NSTextView 包含在 NSViewRepresentable 中,如下所示

struct RichTextField: NSViewRepresentable {
typealias NSViewType = RichTextFieldExtended

@Binding var attributedString: NSAttributedString
var isEditable: Bool

func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeNSView(context: Context) -> RichTextFieldExtended {
let textView = RichTextFieldExtended(frame: .zero)

textView.textStorage?.setAttributedString(self.attributedString)
textView.isEditable = isEditable
textView.delegate = context.coordinator

textView.translatesAutoresizingMaskIntoConstraints = false
textView.autoresizingMask = [.width, .height] 
return textView
}
func updateNSView(_ nsView: RichTextFieldExtended, context: Context) {
//        nsView.textStorage!.setAttributedString(self.attributedString)
}
// Source: https://medium.com/fantageek/use-xib-de9d8a295757
class Coordinator: NSObject, NSTextViewDelegate {
let parent: RichTextField

init(_ RichTextField: RichTextField) {
self.parent = RichTextField
}
func textDidChange(_ notification: Notification) {
guard let textView = notification.object as? RichTextFieldExtended else { return }
self.parent.attributedString = textView.attributedString()
}
}

}

干杯

最新更新