我试图让我的父视图在其子视图的一个属性改变时更新。Binding
但该值从未在父视图中更新 - 只在子视图中更新。
这是一些示例代码,它简化了我的问题。
struct ArrayDisplayWithPageNumber: View {
var arrayDisplay: ArrayDisplay
@Binding var index: Int // This should update when 'index' changes in 'arrayDisplay'.
init() {
self.arrayDisplay = ArrayDisplay()
self._index = self.arrayDisplay.$index
}
var body: some View {
VStack {
arrayDisplay
.padding()
Text("Page number: \(index + 1)") // Stays at "Page number: 1".
}
}
}
struct ArrayDisplay: View {
var greetings: [String] = ["Hello", "Hola", "Bonjour"]
@State var index: Int = 0 // This is the property I want to read in the parent view.
var body: some View {
VStack {
Button("Next greeting") {
if self.index + 1 == self.greetings.count {
self.index = 0 // Simple check to prevent array out of bounds error.
} else {
self.index += 1 // Increments index if it's not at it's highest index value.
}
}
Text(greetings[index])
.font(.title)
}
}
}
我不想合并我所创建的两个视图,所以有什么办法可以读到 index
财产 ArrayDisplay
并有 ArrayDisplayWithPageNumber
变化时更新?
如果你能提供一些解决我问题的代码,并解释为什么我的代码没有工作,这将是非常有用的。
先谢谢你
你混淆了源& 目标的所有权,即依赖方向。这里是固定的变体。用Xcode 11.4 iOS 13.4进行测试。
struct ArrayDisplayWithPageNumber: View {
@State var index: Int = 0 // << here !!
var body: some View {
VStack {
ArrayDisplay(index: $index) // << here !!
.padding()
Text("Page number: \(index + 1)")
}
}
}
struct ArrayDisplay: View {
var greetings: [String] = ["Hello", "Hola", "Bonjour"]
@Binding var index: Int // << and here !!
var body: some View {
VStack {
Button("Next greeting") {
if self.index + 1 == self.greetings.count {
self.index = 0
} else {
self.index += 1
}
}
Text(greetings[index])
.font(.title)
}
}
}
这些链接会有帮助。
使用环境对象 如何使用环境对象 共享数据和更新用户界面