Vic*_*ann 5 swift userdefaults swiftui
我正在 XCode 中开发一个应用程序,该应用程序显示从 URL 保存在 JSON 文件中的位置。我已将用户最喜欢的位置保存在 UserDefaults.standard.object(forKey: "heart") 中
SpotDetailView 上的心形按钮可保存该地点,并显示该地点是否为收藏夹。
import SwiftUI
struct SpotDetailView: View {
@State var spot: WindApp //knows which spot it's at
var spotname:String
@State var favourites: [String:String] = UserDefaults.standard.object(forKey: "heart") as? [String:String] ?? [:]
var body: some View {
ZStack {
List {
SpotMapView(coordinate: spot.locationCoordinate)
.cornerRadius(8)
ForEach(0..<9) { i in
SingleDayView(spot: spot, counter: (i * 8))
}
}
.navigationTitle("\(spot.spot)")
VStack {
Spacer()
HStack {
Spacer()
Button(action: {
if favourites[spot.spot] == "heart" {
favourites[spot.spot] = "heart.fill"
UserDefaults.standard.set(favourites, forKey: "heart")
}
else if favourites[spot.spot] == "heart.fill" {
favourites[spot.spot] = "heart"
UserDefaults.standard.set(favourites, forKey: "heart")
}
else {
favourites[spot.spot] = "heart.fill"
UserDefaults.standard.set(favourites, forKey: "heart")
}
}, label: {
Image(systemName: favourites[spot.spot] ?? "heart")
})
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当尝试访问主概述上的数据时,它会在重新/启动应用程序后起作用,但在子视图中更改时不会更新。
struct AllSpotsView: View {
@State private var spotData = [WindApp]()
@State var favourites: [String: String] = UserDefaults.standard.object(forKey: "heart") as? [String: String] ?? [:]
var body: some View {
ZStack {
NavigationView{
List(spotData, id: \.spot) {
item in
NavigationLink(destination: SpotDetailView(spot: item, spotname: item.spot)) {
HStack() {
Text(item.spot)
Text(item.country_code)
.font(.caption2)
.foregroundColor(.gray)
Spacer()
Image(systemName: favourites[item.spot] ?? "heart" )
}
}.navigationBarTitle("Spots")
}.onAppear(perform: loadData)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
loadData 函数只是从 URL 加载 JSON 文件。一旦 Userdefault 值更改,如何使视图更新?提前致谢!
代替
@State var favourites: [String: String] = UserDefaults.standard.object(forKey: "heart") as? [String: String] ?? [:]
Run Code Online (Sandbox Code Playgroud)
使用
@AppStorage("heart") var favourites: [String: String] = [:]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2108 次 |
| 最近记录: |