首页 > 解决方案 > 选择更改时,通过 NSViewRepresentable 将值从 NSTextView 传递到父 SwiftUI 视图

问题描述

问题

我希望能够从 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 的自定义方法?我必须制作自定义代表吗?

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

标签: swiftswiftuinstextviewnsviewrepresentable

解决方案


推荐阅读