SwiftUI 中的 List 和 ForEach 有什么区别? [英] What is the difference between List and ForEach in SwiftUI?
问题描述
我知道 SwiftUI 目前不支持常规的 for 循环,而是提供了一种叫做 ForEach 的东西,但这和 List 有什么区别?
I know SwiftUI does not support currently regular for loops but instead provide something called ForEach but what is the difference between that and a List?
推荐答案
ForEach
是一个视图,它允许您将一组数据传递给其初始值设定项,然后根据您提供的闭包创建多个子视图".它没有关于如何安排视图的任何语义.ForEach
is a view that lets you pass a collection of data to its initializer and then creates multiple "subviews" from the closure you provide. It doesn't have any semantics on how the views will be arranged.ForEach(1...5) { row in Text("Row \(row)") }
将创建等效的关闭
Text("Row 1") Text("Row 2") Text("Row 3") Text("Row 4") Text("Row 5")
包装在单个容器视图中.
wrapped in a single container view.
List
是一种可以将多个视图组合在一起的视图,但不一定是同一类型的视图.您可以简单地添加多个视图而无需任何循环.List
is a view that can compose multiple views together, but not necessarily views of the same type. You can simply add multiple views without any loop.List { Image("avatar") Text("Title") Button(action: { print("Button tapped!") }) { Text("Energize!") } }
作为一个方便,
List
初始值设定项允许您像使用ForEach
视图一样使用它,以防您想要包含一个列表仅限单一细胞类型.As a convenience, the
List
initializer allows you to use it just like theForEach
view in case you want to have a list consisting of a single cell type only.List(1...5) { row in Text("Row \(row)") }
列表具有特殊的外观,具体取决于平台.例如,在 iOS 上,列表将显示为表格视图,并在其垂直堆叠的视图之间插入分隔线.
A list has a special appearance, depending on the platform. For example, on iOS a list will appear as a table view and insert separator lines between its vertically stacked views.
您可以在
List
视图中使用ForEach
视图来拥有动态和静态内容 - SwiftUI 的一个非常强大的功能.You can use
ForEach
views insideList
views to have both dynamic and static content – a very powerful feature of SwiftUI.List { Text("Food") ForEach(meals) { meal in Text(meal.name) } Text("Drinks") ForEach(drinks) { drink in Text(drink.name) } }
这篇关于SwiftUI 中的 List 和 ForEach 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!