[英]SwiftUI - Increment variable in a ForEach loop doesn't work for some reason
Please help.请帮忙。 I have this in my ContentView
:我的ContentView
有这个:
func makeView() -> Text{
self.index += 1 // add one to this variable
return Text("App")//Return a view
}
ForEach(0..<imageArray.count){ row in
HStack{
ForEach(0..<PartyCollectionViewCell.column){ column in
self.makeView() // Call the function in the content view
PartyCollectionViewCell(cellImg: imageArray[index+1]!)
} //update the cell
}
}
I want to update my "index" variable in PartyCollectionViewCell(celling:imageArray[index+1]!)
to add one to the index
variable.我想更新我在PartyCollectionViewCell(celling:imageArray[index+1]!)
“index”变量以将一个添加到index
变量。
I even created func called makeview as seen below to update it but it doesn't work.我什至创建了如下所示的名为 makeview 的 func 来更新它,但它不起作用。
Instead of increasing index
, compute the index from the row
and column
indices.不是增加index
,而是根据row
和column
索引计算索引。
If your array contains 8 images and you want 2 columns, then you will have 8/2 == 4
rows.如果您的数组包含 8 个图像并且您想要 2 列,那么您将有8/2 == 4
行。 Your outer loop should loop over the number of rows which can be computed as imageArray.count/PartyCollectionViewCell.column
.您的外循环应该遍历可以计算为imageArray.count/PartyCollectionViewCell.column
的行数。
Then the index of the image would be row * PartyCollectionViewCell.column + column
.那么图像的索引将是row * PartyCollectionViewCell.column + column
。
func makeView() -> Text{
return Text("App") //Return a view
}
ForEach(0..<(imageArray.count/PartyCollectionViewCell.column)) { row in
HStack{
ForEach(0..<PartyCollectionViewCell.column) { column in
self.makeView() // Call the function in the content view
PartyCollectionViewCell(cellImg: imageArray[row * PartyCollectionViewCell.column + column]!)
} //update the cell
}
}
// Handle partial row
if (imageArray.count % PartyCollectionViewCell.column > 0) {
HStack {
ForEach((imageArray.count/PartyCollectionViewCell.column)*PartyCollectionViewCell.column..<imageArray.count) { index in
self.makeView()
PartyCollectionViewCell(cellImg: imageArray[index]!)
}
ForEach(0..<(PartyCollectionViewCell.column - imageArray.count % PartyCollectionViewCell.column)) { _ in
EmptyView()
}
}
}
if you are working with collections of images, I suggest you to use:如果您正在处理图像集合,我建议您使用:
struct ContentView: View {
let data = (1...1000).map { "Item \($0)" }
let columns = [
GridItem(.adaptive(minimum: 80))
]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 20) {
ForEach(data, id: \.self) { item in
Text(item)
}
}
.padding(.horizontal)
}
}
}
As wrote here .正如这里所写。 In the link you can find also a solution if you are workin with target iOS13如果您使用目标 iOS13,您还可以在链接中找到解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.