SwiftUI-ForEach是否具有endIndex或lastindex?

标签 swiftui

我正在使用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/

相关文章:

SwiftUI如何防止 View 重新加载整个 body

swiftui - 为什么绑定(bind)到 UIViewRepresentable 的注入(inject)会导致内存泄漏?

ios - SwiftUI 结合 Debounce TextField

swift - LinkPresentation View 未在 SwiftUI 中完全加载

swiftui - 如何获取每个字符在 SwiftUI 文本中的位置

swiftui - 如何从 Swift 类更改 @State var

ios - 在 SwiftUI 中删除列表下方的额外行分隔符

ios - SwiftUI 在主包中找不到命名的图像

ios - @Observable 模型更改未反射(reflect)在 View 中

swift - 我想点击推送通知以在SwiftUI中打开特定屏幕