SwiftUI 迭代列表不应用 listRow 修饰符

SwiftUI iterating List not applying listRow modifiers

我创建了以下List

List {
 Text("Hello")
   .listRowBackground(Color.red)
}

呈现此视图:

当我更改 List 以遍历一个范围时,它停止应用 listRow 修饰符:

List (0 ..< 3) { _ in
  Text("Hello")
    .listRowBackground(Color.red)
}

为什么会这样?

您需要 ForEach。如 doc

中所述

The SwiftUI ForEach structure computes views for each element of the enumeration and extracts the raw value of each of its elements using the resulting text to create each list row item. The listRowBackground(_:) modifier then places the view you supply behind each of the list row items:

所以最后的代码是,

List {
    ForEach(0 ..< 3){  _ in
        Text("Hello")
            .listRowBackground(Color.red)
    }
}