gpt4 book ai didi

swiftui - 对 ObservedObject 的更改不会更新 UIViewRepresentable

转载 作者:行者123 更新时间:2023-12-02 01:16:11 28 4
gpt4 key购买 nike

下面是最简单的例子。在预览中工作正常(UITextView 文本更新为“ouch”)。但是,在应用程序中运行它(即通过 sceneDelegate 添加为 rootView),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

最佳答案

这看起来像是 SwiftUI 的某种错误,但有两种解决方法:

  1. 将字符串作为 @Binding 传递给 MyTextView:
struct MyTextView : UIViewRepresentable {
@Binding var text: String

func makeUIView(context: Context) -> UITextView {
let result = UITextView()
result.isEditable = true
return result
}
func updateUIView(_ view: UITextView, context: Context) {
view.text = text
}
}

struct BugDemoView : View{
@ObservedObject var modelObject = ModelObject()
var body : some View{
VStack{
MyTextView(text: $modelObject.text)
Button(action: {
self.modelObject.text = "ouch"
}){
Text("Button")
}
}
}
}
  • 将字符串传递给MyTextView:
  • struct MyTextView : UIViewRepresentable {
    var text: String

    func makeUIView(context: Context) -> UITextView {
    let result = UITextView()
    result.isEditable = true
    return result
    }
    func updateUIView(_ view: UITextView, context: Context) {
    view.text = text
    }
    }

    struct BugDemoView: View{
    @ObservedObject var modelObject = ModelObject()
    var body: some View{
    VStack{
    MyTextView(text: modelObject.text)
    Button(action: {
    self.modelObject.text = "ouch"
    }){
    Text("Button")
    }
    }
    }
    }

    关于swiftui - 对 ObservedObject 的更改不会更新 UIViewRepresentable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58354063/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com