Reputation: 5
I have a list of data from CoreData using fetch results. And I wanted to put that coredata data to a list of array so that I can save the checkbox state in memory not in the database.
Example:
@FetchRequest(
entity: ParticipantEntity.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \ParticipantEntity.first_name, ascending: true)]
) var participantItems:FetchedResults<ParticipantEntity>
**// is there a way to transfer participantItems to a simple list of object?like:
var newItems : participantItems **
var body: some View {
List {
ForEach(self.participantItems) { participant in
HStack{
AsyncImage(
url: URL(string: url+(participant.profile_picture ?? "")),
content: { image in
image.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxWidth: 45, maxHeight: 45)
.cornerRadius(5)
},
placeholder: {
Image("no_profile_pic")
.resizable()
.frame(maxWidth: 45, maxHeight: 45)
}
)
VStack(alignment: .leading){
let fname = participant.first_name ?? ""
let lname = participant.last_name ?? ""
let name = fname + " " + lname
Text(name)
Text(participant.group_name ?? "No Group Name")
}.padding(.leading, 5.0)
Spacer()
**Image(systemName: participant.isChecked ? "checkmark.square" : "square")
.onTapGesture {
participant.isChecked.toggle()
}**
}
}
}.listStyle(PlainListStyle())
}
@FetchRequest(
entity: ParticipantEntity.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \ParticipantEntity.first_name, ascending: true)]
) var participantItems:FetchedResults<ParticipantEntity>
var newItems = newItems[participantItems]
Upvotes: 0
Views: 579
Reputation: 119242
You don't need to copy the values to a separate array. Have a @State property to hold the selected items:
@State private var selectedParticipants = Set<Participant>()
Then a couple of functions on your view to get and set selection:
private func isSelected(_ participant: Participant) -> Bool {
selectedParticipants.contains(participant)
}
private func toggleSelection(of participant: Participant) {
if isSelected(participant) {
selectedParticipants.remove(participant)
} else {
selectedParticipants.insert(participant)
}
}
So your checkbox would then be:
Image(systemName: isSelected(participant) ? "checkmark.square" : "square")
.onTapGesture {
toggleSelection(of: participant)
}
Upvotes: 1