Skip to main content

How to create a List or a ForEach from a binding

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to create a List or a ForEach from a binding 관련

SwiftUI by Example

Back to Home

How to create a List or a ForEach from a binding | SwiftUI by Example

How to create a List or a ForEach from a binding

Updated for Xcode 15

New in iOS 15

SwiftUI lets us create a List or ForEach directly from a binding, which then provides the content closure with individual bindings to each element in the collection of data we're showing. This is important for the times when the content you're showing for each item needs a binding to some of its data, such as list rows having a text field to edit a user's name.

To use this, pass the binding into your list directly, e.g. $users, then accept a binding in the content closure, e.g. $user. For example, in this code we show a list of users and add to each row a Toggle determining whether they have been contacted or not:

struct User: Identifiable {
    let id = UUID()
    var name: String
    var isContacted = false
}

struct ContentView: View {
    @State private var users = [
        User(name: "Taylor"),
        User(name: "Justin"),
        User(name: "Adele")
    ]

    var body: some View {
        List($users) { $user in
            Text(user.name)
            Spacer()
            Toggle("User has been contacted", isOn: $user.isContacted)
                .labelsHidden()
        }
    }
}

Download this as an Xcode projectopen in new window

Using a binding in this way is the most efficient way of modifying the list, because it won't cause the entire view to reload when only a single item changes.

Similar solutions…
How to create views in a loop using ForEach | SwiftUI by Example

How to create views in a loop using ForEach
What is the @Binding property wrapper? | SwiftUI by Example

What is the @Binding property wrapper?
How to fix “Cannot convert value of type 'String' to expected argument type 'Binding'” | SwiftUI by Example

How to fix “Cannot convert value of type 'String' to expected argument type 'Binding'”
How to animate changes in binding values | SwiftUI by Example

How to animate changes in binding values
Building a menu using List | SwiftUI by Example

Building a menu using List

이찬희 (MarkiiimarK)
Never Stop Learning.