【问题标题】:How to use @AppStorage for a Dictionary of Strings [String: String]如何将@AppStorage 用于字符串字典 [String: String]
【发布时间】:2020-12-20 17:12:15
【问题描述】:

嘿,在我的应用程序中,我正在尝试存储用户是否希望某个位置成为其最喜欢的位置。为了在此 UserDefaults 中进行更改,我需要使用 @AppStorage 更新视图。但是,目前我只收到错误“在调用初始化程序时没有完全匹配”我是否需要使用数据而不是 [字符串:字符串],如果是的话如何?有谁知道如何解决这一问题?提前致谢

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)
                }
            }
        }
    }
}

【问题讨论】:

标签: swift xcode swiftui appstorage


【解决方案1】:

您将不得不使用数据。 @AppStorage 目前只支持:

  • 内部
  • 字符串
  • 布尔
  • 网址
  • 数据

查看sample implementation and further details的这个答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    相关资源
    最近更新 更多