下面最简单的例子。在预览中工作正常(UITextView
文本更新为“哎哟”)。但是,在应用程序中运行它(即rootView
通过添加 as sceneDelegate
),并且UITextView
不会更新。
import SwiftUI
class ModelObject : ObservableObject{
@Published var text = "Model Text"
}
struct MyTextView : UIViewRepresentable {
@ObservedObject var modelObject : ModelObject
func makeUIView(context: Context) -> UITextView {
let result = UITextView()
result.isEditable = true
return result
}
func updateUIView(_ view: UITextView, context: Context) {
view.text = modelObject.text
}
}
struct BugDemoView : View{
@ObservedObject var modelObject : ModelObject
var body : some View{
VStack{
MyTextView(modelObject: modelObject)
Button(action: {
self.modelObject.text = "ouch"
}){
Text("Button")
}
}
}
}
#if DEBUG
var mo = ModelObject()
struct BugDemoView_Preview: PreviewProvider {
static var previews: some View {
BugDemoView(modelObject: mo)
}
}
#endif