我有以下几点看法:
struct GameView: View {
@State private var userWon: Bool = false {
didSet {
print("userWon: \(userWon)") // not called
// TODO: Change game state here
}
}
var body: some View {
ZStack {
VStack {
GameViewRepresentable(userWon: $userWon)
.onChange(of: userWon) { newValue in
print("GameViewRepresentable: \(newValue)") // called
// TODO: or change game state here?
}
}
.clipped()
}
}
}
可表示的视图如下所示:
struct GameViewRepresentable: UIViewRepresentable {
typealias UIViewType = GameView
@Binding var userWon: Bool {
willSet { newValue
print("willSet userWon: \(newValue)")
}
didSet {
print("didSet userWon: \(userWon)")
}
}
func makeUIView(context: Context) -> GameView {
let gameView = GameView()
gameView.delegate = context.coordinator
return gameView
}
func updateUIView(_ uiView: GameView, context: Context) {
}
func makeCoordinator() -> GameViewCoordinator {
GameViewCoordinator(self)
}
class GameViewCoordinator: GameViewDelegate {
var parent: GameViewRepresentable
init(_ parent: GameViewRepresentable) {
self.parent = parent
}
func userWon() {
self.parent.userWon = true
}
}
}
我可以看到,在协调器内部正确地调用了userWon
方法,该协调器相应地调用了GameViewRepresentable
中的willSet
和didSet
,但是绑定userWon
属性的GameView
中的didSet
从未被调用.然而,Gameview中的onChange
确实会被调用.那么,这是应对国有assets资源 变化的正确方式吗?我原以为会调用Gameview中的didSet
.