I am trying to use AppStorage
to hold a list of id
's for my Country
struct. I want to persist this list of id
's as favorites for a user and if it's a favorite, have the heart next to each country filled.
If they tap the heart to unfavorite it, it will remove the id
from the favLists
and if they tap it to favorite it, it will add it to the list.
This is not working as I expect and I am not sure what I am doing wrong here.
struct Number: Identifiable, Codable {
var id: Int
}
struct ContentView: View {
@Binding var countries: [Country]
@Namespace var namespace;
@AppStorage("favLists") var favLists: [Number] = [];
var body: some View {
GeometryReader { bounds in
NavigationView {
ScrollView {
ForEach(Array(filteredCountries.enumerated()), id: \.1.id) { (index,country) in
LazyVStack {
ZStack(alignment: .bottom) {
HStack {
NavigationLink(
destination: CountryView(country: country),
label: {
HStack {
Image(country.image)
.resizable()
.frame(width: 50, height: 50)
Text(country.display_name)
.foregroundColor(Color.black)
.padding(.leading)
Spacer()
}
.padding(.top, 12.0)
}
).buttonStyle(FlatLinkStyle())
if (favLists.filter{$0.id == country.id}.count > 0) {
Image(systemName: "heart.fill").foregroundColor(.red).onTapGesture {
let index = favLists.firstIndex{ $0.id == country.id}
if let index = index {
favLists.remove(at: index)
}
}
.padding(.top, 12)
} else {
Image(systemName: "heart").foregroundColor(.red).onTapGesture {
favLists.append(Number(id: country.id))
}
.padding(.top, 12)
}
}
.padding(.horizontal, 16.0)
}
}
}
}
.frame(maxWidth: bounds.size.width)
.navigationTitle("Countries")
.font(Font.custom("Avenir-Book", size: 28))
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
}