Reputation: 79
world! I work in SwiftUI, I want to use data from CoreData in label.
Use likedDBE.isLiked
instead of cellViewModel.isLiked
. How can this be implemented?
Button(action: {
let likedDBE = LikedDBE(context: self.managedObjectContext)
likedDBE.name = cellViewModel.card.name
likedDBE.price = cellViewModel.card.price
likedDBE.isLiked = cellViewModel.isLiked
do{
try self.managedObjectContext.save()
}catch {
print(error)
}
}, label: {
Image(systemName: cellViewModel.isLiked ? "heart.fill" : "heart") //In this place
.frame(width: 22, height: 22)
.foregroundColor(cellViewModel.isLiked ? .red : .black) //And in this place
})
Thank you all in advance!
Upvotes: 0
Views: 80
Reputation: 36647
you cannot use likedDBE.isLiked
in the Button label
part, because it is only available in the Button action
part. So
move the likedDBE
outside the Button
action
, for example:
// somewhere appropriate in your code and accessible to the button
var likedDBE = LikedDBE(context: self.managedObjectContext)
likedDBE.name = cellViewModel.card.name
likedDBE.price = cellViewModel.card.price
likedDBE.isLiked = cellViewModel.isLiked
// just keep the saving in the button action.
Button(action: {
do{
try self.managedObjectContext.save() // <--- here keep this
}catch {
print(error)
}
}, label: {
Image(systemName: likedDBE.isLiked ? "heart.fill" : "heart") // <--- here can use likedDBE
.frame(width: 22, height: 22)
.foregroundColor(likedDBE.isLiked ? .red : .black) // <--- here can use likedDBE
})
Upvotes: 1