[我正在尝试更改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
。
谢谢!
您必须绑定至少一个值才能使update
工作,因为只有绑定才能使UIViewController加入通知链。
如果使用@state,它将是本地通知,无法触发update
。
现在您可以@Binding var blah: Int
查看较大的更改。