0

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

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

现在,我想在 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 制作富文本编辑器。我怎样才能实现它?能给我一些关键字吗?一些回购?

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

4

1 回答 1

0

使用@Binding和委托。

UIView 可表示的视图

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)")
        }
    }
}

于 2021-01-15T13:38:41.787 回答