我正在使用ForEach创建一个循环。但是,我想根据循环的数量有条件地渲染Rectangle。例如,如果最后一次循环迭代,则不要渲染矩形。
正确的语法是什么?
我正在寻找这样的东西(不工作的伪代码)
ForEach(arrayOfThings, id: \.title) { thing in
// Stuff that happens on every iteration of loop
// Conditional section
if (thing.endIndex-1) {
Rectangle()
.frame(width: 100, height: 1, alignment: .bottom)
.foregroundColor(Color("666666"))
}
}
我知道有些东西像
for (offset, element) in array.enumerated() { }
,但是您不能在 View 中使用它们。我想知道ForEach中是否有便利功能来解决此需求?目前,我正在这样做以解决此问题:
ForEach(0..<arrayOfThings.count) { i in
// Stuff that happens on every iteration of loop
// Conditional section
if (i = self.arrayOfThings.count-1) {
Rectangle()
.frame(width: 100, height: 1, alignment: .bottom)
.foregroundColor(Color("666666"))
}
}
最佳答案
如果您的arrayOfThings是Equatable,则可以这样做
ForEach(arrayOfThings, id: \.title) { thing in
if thing == arrayOfThings.last {
// do something
}
}
在我看来,这比检查索引与计数更具可读性。
关于SwiftUI-ForEach是否具有endIndex或lastindex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58394587/