UPDATE: Let's put it very simple. This:
struct FavoriteButton: View {
@Binding var items : [Item]
var body: some View {
Button("Toggle") {
.....
}
}
}
You have the item at your disposal, not the array to pass in FavoriteButton(items: [something])
. If you just create the array it will break the binding as it is the struct not the class and it will not keep the reference. Can you pass it somehow and keep the binding?
ORIGINAL QUESTION (which also explains why):
I have a List
in SwiftUI. Let's say that it is bound to [Item]
array and that there is a property Item.isFavorite
that triggers visual change in a row. The item should be handled by the FavoriteButton
that can be triggered by the single item like in swipeActions
or by multiple items like in contextMenu(forSelection:)
.
The question is whether it is possible to do this by passing an item array to the button? My problem is that array needs to be passed as the binding so that changing of the isFavorite
updates the view, and if I create a new array from the single item I seem to be unable to keep the binding.
One possible solution is to pass the item id array and then do the work in the view model (this way I don't need to keep the binding in the button). However I am particularly interested in whether it is possible to be done by passing the item array to the button and binding. I am aware that the solution with just using ids and view model might be better, but for some curiosity I am interested if this is possible (I think it should be).
EDIT: as some people asked for clarification, I'll copy it from my comment below where I have provided it:
You have a FavoriteButton
view that has @Binding var items : [Item]
. You only have Item (not an array) when creating the FavoriteButton
at your disposal. How do you pass it as the array that keeps the binding to the original item?