Created
April 7, 2020 02:42
-
-
Save pescode/f59a5977eb140b1bdcca2d18f31aa0f9 to your computer and use it in GitHub Desktop.
Getting the index number of an item in an Array of Identifiables
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 IdentifiableListView: View { | |
@State var userList = [ | |
Users(name: "Sarah", lastName: "Gates"), | |
Users(name: "Jack", lastName: "Black"), | |
Users(name: "Kate", lastName: "Anderson"), | |
Users(name: "Bill", lastName: "Jobs"), | |
Users(name: "Steve", lastName: "Gates") | |
] | |
var body: some View { | |
List { | |
ForEach(Array(userList.enumerated()), id: \.1.id) { (index, item) in | |
HStack { | |
VStack { | |
Text(item.name) | |
Text(item.lastName) | |
} | |
.frame(maxWidth:.infinity) | |
.frame(alignment:.center) | |
Spacer() | |
} | |
.padding() | |
.background(index%2==0 ? Color.yellow:Color.orange) | |
} | |
.onDelete{ index in | |
self.userList.remove(at: index.first!) | |
} | |
} | |
} | |
} | |
struct IdentifiableListView_Previews: PreviewProvider { | |
static var previews: some View { | |
IdentifiableListView() | |
} | |
} | |
struct Users: Identifiable{ | |
var id = UUID() | |
var name: String | |
var lastName: String | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment