SwiftUI 循环生成组件:使用 ForEach 遍历数据
在 SwiftUI 中,可以使用 ForEach 循环遍历数组或其他序列,并生成多个组件。ForEach 接收一个序列作为输入,然后将序列中的每个元素转换为一个组件。
简单示例:
struct ContentView: View {
let items = ['Item 1', 'Item 2', 'Item 3']
var body: some View {
VStack {
ForEach(items, id: \.self) { item in
Text(item)
}
}
}
}
在上面的示例中,我们定义了一个字符串数组 items,然后使用 ForEach 遍历该数组并将每个元素转换为一个 Text 组件。我们还指定了一个 id 参数,这告诉 SwiftUI 如何识别和更新列表中的元素。
使用 Identifiable 协议:
ForEach 可以接受任何遵循了 Identifiable 协议的类型。如果你的数据类型没有遵循该协议,可以使用带有 id 参数的 ForEach 来手动指定一个唯一标识符。例如:
struct Item: Identifiable {
let id = UUID()
let name: String
}
struct ContentView: View {
let items = [
Item(name: 'Item 1'),
Item(name: 'Item 2'),
Item(name: 'Item 3')
]
var body: some View {
VStack {
ForEach(items, id: \.id) { item in
Text(item.name)
}
}
}
}
在上面的示例中,我们定义了一个 Item 结构体,并使其遵循了 Identifiable 协议。然后,我们使用 ForEach 遍历 Item 数组并将每个元素转换为一个 Text 组件。注意,我们使用了 item.id 作为标识符。
原文地址: https://www.cveoy.top/t/topic/njUv 著作权归作者所有。请勿转载和采集!