Here is my sample. I have a list with something to sum up. And I set up an Observe obj to store the result, trigger +1 when the subview on Appear.
class observed : ObservableObject {
@Published var listNum : Int = 0
}
struct ContentView: View {
@State private var mylist = [
1,0,1,0,1,1
]
var body: some View {
ForEach(mylist, id: \.self) { (value) in
ExtractedView(value:value)
}
}
}
struct ExtractedView: View {
var value : Int = 0
@EnvironmentObject var obj : observed
@State var listNum:String = "0"
var body: some View {
Text(listNum)
.onAppear{
if self.value != 1{
self.obj.listNum = 0
}else{
self.obj.listNum += 1
}
self.listNum = String(self.obj.listNum)
}
}
}
But the result always Upside down, not as expected.
Actually order of .onAppear
call is undefined, so it is not clear what is expected. Anyway from what I see in provided code there might be confuse for ForEach
id, `cause array value is used, but it is not unique.
Try the following
ForEach(Array(mylist.enumerated()), id: \.0) { (i, value) in
ExtractedView(value:value)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.