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

问题描述 投票:0回答:1

[我正在尝试更改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
    }
  }
}

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

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

谢谢!

ios swift swiftui
1个回答
0
投票

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

如果使用@state,它将是本地通知,无法触发update

现在您可以@Binding var blah: Int查看较大的更改。

© www.soinside.com 2019 - 2024. All rights reserved.