Updated for Xcode 12.0
In order to handle dynamic items, you must first tell SwiftUI how it can identify which item is which. This is done using the Identifiable
protocol, which has only one requirement: some sort of id
value that SwiftUI can use to see which item is which.
For example, you might create a Restaurant
struct that says restaurants have an ID and name, with the ID being a random identifier just so that SwiftUI knows which is which:
struct Restaurant: Identifiable {
var id = UUID()
var name: String
}
Next you would define what a list row looks like. In our case we’re going to define a RestaurantRow
view that stores one restaurant and prints its name in a text view:
struct RestaurantRow: View {
var restaurant: Restaurant
var body: some View {
Text("Come and eat at \(restaurant.name)")
}
}
Finally we can create a list view that shows them all. This means creating some example data, putting it into an array, then passing that into a list to be rendered:
struct ContentView: View {
var body: some View {
let first = Restaurant(name: "Joe's Original")
let second = Restaurant(name: "The Real Joe's Original")
let third = Restaurant(name: "Original Joe's")
let restaurants = [first, second, third]
return List(restaurants) { restaurant in
RestaurantRow(restaurant: restaurant)
}
}
}
Most of that is just creating data – the last part is where the real action is:
return List(restaurants) { restaurant in
RestaurantRow(restaurant: restaurant)
}
That creates a list from the restaurants
array, executing the closure once for every item in the array. Each time the closure goes around the restaurant
input will be filled with one item from the array, so we use that to create a RestaurantRow
.
In fact, in trivial cases like this one we can make the code even shorter:
return List(restaurants, rowContent: RestaurantRow.init)
SPONSORED Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.