问题描述
嘿,在我的应用程序中,我试图存储用户是否希望某个位置成为其最喜欢的位置。为了使此 UserDefaults 中的更改更新视图,我需要使用 @AppStorage。但是,目前我只收到错误“调用初始化程序时没有完全匹配”我是否需要使用数据而不是 [String: String],如果是,如何?有谁知道如何解决这一问题?提前致谢
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] ?? [:]
@AppStorage("heart") var favourites: [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")
})
.frame(width: 20,height: 20)
}
}
}
}
}