📅  最后修改于: 2023-12-03 15:35:12.934000             🧑  作者: Mango
SwiftUI is a modern, declarative user interface framework for building iOS, iPadOS, macOS, watchOS, and tvOS apps. ForEach
is a view that allows you to create a dynamic list of views from an array, a set, or a range.
ForEach<Data, ID, Content>(
_ data: Data,
id: KeyPath<Data.Element, ID>,
content: (Data.Element) -> Content
) -> some View where Data : RandomAccessCollection, ID : Hashable, Content : View
data
: The collection of data that is used to create the views.id
: A key path to a property on the data that uniquely identifies each element. The identified elements must be hashable.content
: A closure that returns the content of the view for each element in the data
collection.struct ContentView: View {
let languages = ["Swift", "Objective-C", "Java", "Python", "Ruby", "Kotlin"]
var body: some View {
List {
ForEach(languages, id: \.self) { language in
Text(language)
}
}
}
}
In the above example, we have an array of programming languages. We create a dynamic list of Text
views by iterating over the languages
array using ForEach
. The id: \.self
parameter specifies that the languages
array is identified by its own values, and the closure provides the content for each row in the list.
ForEach
is a powerful tool in SwiftUI for creating dynamic lists of views. It is useful for iterating over collections of data and generating views based on each element in the collection. By using ForEach
, we can keep our code clean and maintainable.