【发布时间】:2020-06-04 14:29:06
【问题描述】:
RichTextView 是一个 UIView 包。不能如下使用:
import SwiftUI
import RichTextView
struct ContentView1: View {
var body: some View {
VStack {
RichTextView( // <-- Wrong!
input: "Test",
latexParser: LatexParser(),
font: UIFont.systemFont(ofSize: UIFont.systemFontSize),
textColor: UIColor.black,
isSelectable: true,
isEditable: false,
latexTextBaselineOffset: 0,
interactiveTextColor: UIColor.blue,
textViewDelegate: nil,
frame: CGRect.zero,
completion: nil
)
}
}
}
我还找到参考How to wrap a custom UIView for SwiftUI 如下:
struct TextView: UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UITextView {
return UITextView()
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
}
}
struct ContentView : View {
@State var text = ""
var body: some View {
TextView(text: $text)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}
}
但我尝试了很多方法来使用RichTextView 和UIViewRepresentable。它仍然不起作用。如下:
struct RichTextView: UIViewRepresentable {
@Binding var text: String
let richTextView = RichTextView(
input: text, <-- Cannot use instance member 'text' within property initializer; property initializers run before 'self' is available
latexParser: LatexParser(),
font: UIFont.systemFont(ofSize: UIFont.systemFontSize),
textColor: UIColor.black,
isSelectable: true,
isEditable: false,
latexTextBaselineOffset: 0,
interactiveTextColor: UIColor.blue,
textViewDelegate: nil,
frame: CGRect.zero,
completion: nil
)
func makeUIView(context: Context) -> UITextView {
return UITextView()
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = richTextView <--- changed
}
}
更新:以下仍然不起作用。
struct RichTextView: UIViewRepresentable { <-- Error:Type 'RichTextView' does not conform to protocol 'UIViewRepresentable'
@Binding var text: String
func makeUIView(context: Context) -> RichTextView {
return RichTextView( <-- Error:Extra arguments at positions #1, #2, #3, #4, #5, #6, #7, #8, #9, #10, #11 in call
input: text, <-- Error:Missing argument for parameter 'text' in call
latexParser: LatexParser(),
font: UIFont.systemFont(ofSize: UIFont.systemFontSize),
textColor: UIColor.black,
isSelectable: true,
isEditable: false,
latexTextBaselineOffset: 0,
interactiveTextColor: UIColor.blue,
textViewDelegate: nil,
frame: CGRect.zero,
completion: nil
)
}
func updateUIView(_ richTextView: RichTextView, context: Context) {
richTextView.text = text
}
}
如何制作?感谢您的帮助。
【问题讨论】:
-
您能否展示您使用
UIViewRepresentable方法尝试的代码?这将是要走的路,所以也许你只是错过了一些东西。 -
@Losiowaty 问题已更新。