为什么不更改为@ObservedObject会更新UIViewRepresentable?

时间:2019-11-18 14:00:11

标签: ios swift swiftui

我有一个简单的示例,其中我在父视图中创建@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: ", ")
  }
}

2 个答案:

答案 0 :(得分:0)

尝试一下:

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: ", ")
  }
}

答案 1 :(得分:0)

这可能以非常简单的方式为您提供帮助:

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

尝试使用我添加的行,这将使View自行更新。确保使用:

import Combine