一个包装集合,它使用底层集合提供带有索引的项目,而无需分配内存。
在 SwiftUI 中,我们可能会使用以下技术在 ForEach
中使用索引。
ForEach(Array(array.enumerated()), id: \.offset) { ... }
ForEach(zip(array.indices, array), id: \.0) { ... }
存在以下缺点 (Cúnzài yǐxià quēdiǎn)
enumerated
从 0 提供索引,因此在使用切片时会造成错误的访问 (enumerated
cóng 0 tígōng suǒyǐn, yīncǐ zài shǐyòng qiēpiàn shí huì zàochéng cuòwù de fǎngwèn)。#Preview {
VStack {
ForEach.init(IndexedCollection([1, 2, 3, 4, 5]), id: \.index, content: { e in
Text("\(e.index): \(e.value)")
})
}
}
struct IdentifiableItem: Identifiable {
let id: String
let value: UUID = .init()
}
#Preview {
VStack {
ForEach.init(IndexedCollection(["a", "b", "c", "d", "e"].map(IdentifiableItem.init(id:))), content: { e in
Text("\(e.index): \(e.value)")
})
}
}
在 iOS18 中使用 Group 新 API。反转视图集合中的 z-index (Zài iOS18 zhōng shǐyòng Group xīn API. Fǎnzhuǎn shìtú jíhé zhōng de z-index)。
public struct ReversedZIndex<Content: View>: View {
private let content: Content
public init(@ViewBuilder content: () -> Content) {
self.content = content()
}
public var body: some View {
Group(
subviewsOf: content,
transform: { collection in
let count = collection.count
ForEach(IndexedCollection(collection), id: \.id) { element in
element.value
.zIndex(Double(count - element.index))
}
}
)
}
}