【发布时间】:2023-03-09 07:25:02
【问题描述】:
我的主要视图是解码 JSON,然后枚举该 JSON 以显示城镇列表,您可以在其中切换 favorite 字段。
我想有一个单独的视图来只显示favorited 的城镇,我怀疑我想使用 ObservableObject 和@Published 来监听countries 的变化。我只是不知道如何实现这一点,因为我没有使用任何 class 对象。
Towns.json
[
{
"display_name": "California",
"favorite": false,
},
{
"display_name": "Colorado",
"favorite": false,
}
]
Town.swift
struct Town: Codable, Identifiable {
var id: String {image}
let display_name: String
var favorite: Bool
}
MainView.swift
struct ContentView : View {
@State var towns : [Town] = Bundle.main.decode("Towns.json")
var body: some View {
ForEach(Array(towns.enumerated()), id: \.1.id) { (index,town) in
LazyVStack(spacing: 20) {
HStack {
Text(town.display_name)
Spacer()
Button {
towns[index].favorite.toggle()
} label: {
if town.favorite {
Image(systemName: "flame").foregroundColor(.red)
} else {
Image(systemName: "flame.fill").foregroundColor(.red)
}
}
}
}
}
}
}
【问题讨论】:
标签: swift swiftui swiftui-list