Created
February 26, 2020 20:34
-
-
Save EverybodyKurts/8abad448a4c562b22573f4dfc8cd1147 to your computer and use it in GitHub Desktop.
Creating custom bindings for an element inside a collection.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct Person: Identifiable { | |
let id = UUID() | |
var firstName: String | |
var lastName: String | |
} | |
struct PersonField: View { | |
@Binding var person: Person | |
var body: some View { | |
HStack { | |
TextField("First Name", text: $person.firstName).border(Color.black) | |
TextField("Last Name", text: $person.lastName).border(Color.black) | |
} | |
} | |
} | |
struct PeopleList: View { | |
@State var people: [Person] | |
func personIndex(_ person: Person) -> Int { | |
people.firstIndex(where: { $0.id == person.id })! | |
} | |
var body: some View { | |
VStack { | |
List { | |
ForEach(people) { person in | |
PersonField(person: | |
Binding( | |
get: { person }, | |
set: { updatedPerson in | |
self.people[self.personIndex(updatedPerson)] = updatedPerson | |
}) | |
) | |
} | |
} | |
ForEach(people) { person in | |
Text("\(person.firstName) \(person.lastName)") | |
} | |
} | |
} | |
} | |
struct PeopleList_Previews: PreviewProvider { | |
static var previews: some View { | |
PeopleList(people: [ | |
Person(firstName: "Kurt", lastName: "Mueller"), | |
Person(firstName: "Dustin", lastName: "Perzanowski"), | |
Person(firstName: "Chris", lastName: "Guard") | |
]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment