【发布时间】:2021-12-27 17:59:03
【问题描述】:
我有一个Country 模型,然后是一个国家/地区的 JSON 列表。我使用ForEach 创建了列表。如果搜索框为空,则filteredCountries 的值只是整个列表,否则列表仅包含搜索框中包含whats 的国家/地区。
问题是当列表被过滤并且我点击favorite 一个项目时,错误的国家被收藏了。索引与过滤后的项目不匹配,它们仍然按顺序排列:0,1,2,3 等。
国家
import Foundation
struct Country: Codable, Identifiable {
var id: String {image}
let display_name: String
let searchable_names: [String]
let image: String
var favorite: Bool
var extended: Bool
}
内容视图
var filteredCountries : [Country] {
if (searchText.isEmpty) {
return countries;
} else {
return countries.filter { $0.display_name.contains(searchText) }
}
}
NavigationView {
ScrollView {
ForEach(Array(filteredCountries.enumerated()), id: \.1.id) { (index,country) in
LazyVStack {
ZStack(alignment: .bottom) {
Image("\(country.image)-bg")
.resizable()
.scaledToFit()
.edgesIgnoringSafeArea(.all)
.overlay(Rectangle().opacity(0.2))
.mask(
LinearGradient(gradient: Gradient(colors: [Color.black, Color.black.opacity(0)]), startPoint: .center, endPoint: .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 country.favorite {
Image(systemName: "heart.fill").foregroundColor(.red).onTapGesture {
print(country)
countries[index].favorite.toggle()
}
.padding(.top, 12)
} else {
Image(systemName: "heart").foregroundColor(.red).onTapGesture {
print(country)
countries[index].favorite.toggle()
}
.padding(.top, 12)
}
}
.padding(.horizontal, 16.0)
}
}
.padding(.bottom, country.extended ? 220 : 0)
.onTapGesture {
withAnimation(.easeInOut(duration: 0.4)) {
self.countries[index].extended.toggle();
}
}
}
}
.frame(maxWidth: bounds.size.width)
.navigationTitle("Countries")
.font(Font.custom("Avenir-Book", size: 28))
}
.navigationViewStyle(StackNavigationViewStyle())
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search Country")
【问题讨论】: