从NSTextView传递到Parent Swifui在选择变更时通过NSViewRepresentable查看父SWIFUI视图

问题描述

问题

我希望能够从 textView.textStorage 和/或 textView 的打字属性的选定范围传递文本属性。这应该在选择更改时发生。

这样做的目的是使 SwiftUI 视图可以根据用户使用的属性进行更新。

我正在尝试使用 textViewDidChangeSelection 方法执行此操作。但是,使用 NSTextViewDelegate 时,我只能获取选定的范围,而无法传递从其中的 textView 存储的任何值。

我的尝试

下面是我的 RepresentableView 的精简版。

import SwiftUI

struct TextViewMacOS: NSViewRepresentable {

    @Binding var currentTypingAttributes: [NSAttributedString.Key : Any]
    @Binding var currentTextAttributes: [NSAttributedString.Key : Any]

    class Coordinator: NSObject,NSTextViewDelegate {
        var parent: TextViewMacOS

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

        func textViewDidChangeSelection(_ notification: Notification) {

            /*
            //  Trying to do something like below:
            //  parent.currentTypingAttributes = textView.typingAttributes
            //  parent.currentTextAttributes = textView.textStorage?.attributes(at: textView.selectedRange().lowerBound,effectiveRange: nil)
            */

        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    public func makeNSView(context: Context) -> NSTextView {
        //[...]
    }

    public func updateNSView(_ textView: NSTextView,context: Context) {
        //[...]
    }

}

是否可以创建订阅相同通知但传递 textView 的自定义方法?我必须制作自定义委托吗?

任何帮助将不胜感激。干杯。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)