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

时间:2019-10-29 11:40:14

标签: ios swift swiftui

我正在尝试更改UIViewControllerRepresentable的{​​{1}},并注意到我这样做后并未调用@State

我无法确定这是错误还是我做错了。

例如:

updateUIViewController(_ uiViewController:context:)

我希望看到viewController的背景发生变化,但是更新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 } } } 时根本不会调用updateUIViewController

我还尝试过传递绑定并使用blah

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

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