我希望我是错的,但我找不到SwiftUI中可编辑UITextView的等效物。因此,我使用UIViewRepresentable构建了一个。使用ObservableObject填充SwiftUI文本和我的视图都可以工作 - 但在我的视图中进行的更新没有传播到ObservableObject。我一定漏掉了与Binding概念有关的重要内容。如果有任何指导,将不胜感激。
import SwiftUI
import Combine
struct ContentView: View {
@ObservedObject var myOText: MyOText
var body: some View {
ScrollView {
VStack {
Text("This is a bound Text View")
.padding(.top, 10)
.font(.headline)
Text(myOText.inTheCourse)
.lineLimit(3)
.padding()
Text("This is a multi-line UITextView wrapper:")
.font(.headline)
MultilineTextView(myOText: myOText)
.frame(height: 100)
.padding()
Spacer()
}
}
}
}
struct MultilineTextView: UIViewRepresentable {
@ObservedObject var myOText: MyOText
func makeUIView(context: Context) -> UITextView {
let view = UITextView()
view.isScrollEnabled = true
view.isEditable = true
view.isUserInteractionEnabled = true
view.textAlignment = .center
view.font = UIFont(name: "Times New Roman", size: 20)
return view
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = myOText.inTheCourse
}
}
class MyOText: ObservableObject {
@Published var inTheCourse: String = "When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them ..."
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(myOText: MyOText())
}
}
inTheCourse
是否会传播到您的 UIKit 视图?我之所以问,是因为在我的情况下,在我的@ObservedObject
中进行更改不会触发updateUIViewController
(在我的情况下使用UIViewControllerRepresentable
)。 - Rivera