我有一个简单的示例,其中在父视图中创建@ObservedObject并将其传递给子UIViewRepresentable。当我单击“按钮”时,它会修改@ObservableObject,但是子视图永远不会更新(即,永远不会调用updateUIView)。有其他方法可以做到这一点吗?

import SwiftUI

class UpdateViewState: ObservableObject {
  @Published var words = ["A", "B", "C"]

  func addWord(word: String) {
    print("added word")
    words.append(word)
  }
}

struct UpdateView: View {
  @ObservedObject private var state = UpdateViewState()

  var body: some View {
    VStack {
      UpdateViewRepresentable(state: state)
      Text("Button").onTapGesture {
        self.state.addWord(word: "A")
      }
    }
  }
}

struct UpdateViewRepresentable: UIViewRepresentable {
  @ObservedObject var state: UpdateViewState

  func makeUIView(context: Context) -> UILabel {
    let view = UILabel()
    view.text = "Hello World"
    return view
  }

  func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<UpdateViewRepresentable>) {
    print("updateUIView")
    uiView.text = state.words.joined(separator: ", ")
  }
}

最佳答案

尝试这个:

public final class UpdateViewState: ObservableObject {

  @Published var words = ["A", "B", "C"]

  func addWord(word: String) {
    print("added word ", words)
    words.append(word)
  }
}

struct ContentView: View {

 @EnvironmentObject private var state: UpdateViewState

  var body: some View {
    VStack {
        UpdateViewRepresentable(state: .constant(state))
      Text("Button").onTapGesture {
        self.state.addWord(word: "A")
      }
    }.onAppear() {
        self.state.words.append("aha")
    }
  }
}

struct UpdateViewRepresentable: UIViewRepresentable {

    @Binding var state: UpdateViewState

  func makeUIView(context: Context) -> UILabel {
    let view = UILabel()
    view.text = "Hello World"
    return view
  }

  func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<UpdateViewRepresentable>) {
    print("updateUIView")
    uiView.text = state.words.joined(separator: ", ")
  }
}

关于ios - 为什么不更改为@ObservedObject会更新UIViewRepresentable?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58916278/

10-10 13:29