更新@State 后未调用 SwiftUI UIViewControllerRepresentable.updateUIViewController

dos*_*der 6 ios swift swiftui

我试图改变UIViewControllerRepresentable@State,并注意到updateUIViewController(_ uiViewController:context:)我后不会被调用。

我不知道这是一个错误还是我做错了什么。

例如:

struct ContentView: UIViewControllerRepresentable {
  @State var blah: Int = 0

  func makeUIViewController(context: UIViewControllerRepresentableContext<ContentView>) -> UIViewController {
    let vc = UIViewController()
    let button = UIButton(frame: CGRect(x: 40, y: 40, width: 100, height: 100))
    button.setTitle("Next", for: .normal)
    button.addTarget(context.coordinator, action: #selector(context.coordinator.nextPressed), for: .primaryActionTriggered)
    vc.view.addSubview(button)
    return vc
  }

  func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<ContentView>) {
    // Not being called when `blah` is updated.
    var random = SystemRandomNumberGenerator()
    let red = CGFloat(Double(random.next() % 255) / 255.0)
    let blue = CGFloat(Double(random.next() % 255) / 255.0)
    let green = CGFloat(Double(random.next() % 255) / 255.0)
    uiViewController.view.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
  }


  func makeCoordinator() -> ContentView.Coordinator {
    return Coordinator(self)
  }


  final class Coordinator {
    var contentView: ContentView
    init(_ contentView: ContentView) {
      self.contentView = contentView
    }

    @objc func nextPressed() {
      // This is getting called.
      contentView.blah += 1
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望看到 viewController 的背景发生变化,但是updateUIViewControllerblah更新时我根本看不到被调用。

我也尝试过传入绑定并使用@ObservableObject.

谢谢!

E.C*_*oms 7

您必须绑定至少一个值才能工作,update因为只有绑定才能使 UIViewController 加入通知链。

如果使用@state,则为本地通知,无法触发update.

现在您可以@Binding var blah: Int看到巨大的变化。