将数据更改从 UIKit、包装在 UIViewRepresentable 中发送到 SwiftUI 和富文本编辑器问题

问题描述

我正在做一个 SwiftUI 项目,它需要的功能是在 IOS 上制作富文本编辑器。

我采用的方法相当简单,我使用了最初用 UIKit 编写的 cbess/RichTextEditor link 并将其导入 SwiftUI。为了运行导入的 UIView,我将视图包装在一个 UIViewRpresentable 中,并将其添加到 SwiftUI 的 ContentView struct 中。

现在,我想在 UIView 中发布数据并将其分配给 @state ContentView 拥有的其中之一。

代码结构类似于:

对于 ContentView (SwiftUI)

struct ContentView: View { 
    @State var textHtml: String = "" //I want all changes come from UIView be stored inside this
    var body: some View {
        vstack {
            Cbess(
                frameEditor: CGRect(x: 0,y: 40,width: 360,height: 400)
            )
        }
    }
}

对于 UiViewRepresentable

struct Cbess : UIViewRepresentable{

    let frameEditor : CGRect

    func makeUIView(context: Context) -> UIView {
        
        let frameEditor = RichEditorView(frame: frameEditor)
        
        let uiView : UIView = UIView()
        uiView.addSubview(editorView)
        return uiView
    }
    
    func updateUIView(_ uiView: UIView,context: Context) {
    }
}

对于 UiView(简化)

@objcmembers open class RichEditorView: UIView,{
    var contentHTML : String // This variable get updated regularly

}

另外一个问题是,我想仅通过 SwiftUI 来制作富文本编辑器。我怎样才能实现它?你能给我一些关键词吗?一些回购?

非常感谢任何帮助!感谢您阅读整个问题。

解决方法

使用 @Binding 和委托。

UIViewRepresentable 视图

struct Cbess : UIViewRepresentable {
    
    @Binding var textHtml: String
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIView(context: Context) -> RichEditorView {
        
        let editorView = RichEditorView()
        editorView.delegate = context.coordinator
        return editorView
    }
    
    func updateUIView(_ uiView: RichEditorView,context: Context) {
    }
    
    class Coordinator: NSObject,RichEditorDelegate {
        
        var parent: Cbess
        
        init(_ parent: Cbess) {
            self.parent = parent
        }
        
        // Use delegate here
        func richEditor(_ editor: RichEditorView,contentDidChange content: String) {
            self.parent.textHtml = content
            print(content)
        }
    }
}

您的内容视图:

struct ContentView: View {
    @State var textHtml: String = ""
    var body: some View {
        VStack {
            Cbess(textHtml: $textHtml)
                .frame(width: 360,height: 400)
            
            Text("Print----\n\(textHtml)")
        }
    }
}