如何在SwiftUI中的数组上使用UserDefault

如何在SwiftUI中的数组上使用UserDefault,swiftui,Swiftui,我正在开发一个清单应用程序,它有几个带有检查的数组。如果用户关闭/退出应用程序,我想保存状态。我正在考虑使用UserDefault方法进行此操作: HStack { ForEach(0 ..< checklist.steps) { index in VStack { Button(action: { self.checked[index].toggl

我正在开发一个清单应用程序,它有几个带有检查的数组。如果用户关闭/退出应用程序,我想保存状态。我正在考虑使用UserDefault方法进行此操作:

HStack {
          ForEach(0 ..< checklist.steps) { index in
               VStack {
                    Button(action: {
                          self.checked[index].toggle()
                          UserDefaults.standard.set(self.checked[index], forKey: "Check")
有人知道如何为数组应用UserDefaults,或者通常知道如何在关闭应用程序时保存应用程序的状态吗?
提前谢谢

我还没有测试这个解决方案,但是你不能在每次按钮操作后将数组存储到NSUserdefaults中吗

Button(action: {
    self.checked[index].toggle()
    UserDefaults.standard.set(self.checked, forKey: "Check")
最好的解决方案可能是使用
CoreData
,这将非常容易使用


PS:我可以稍后测试该解决方案。。现在不在我的Mac电脑上

我还没有测试该解决方案,但你不能在每次按钮操作后将数组存储在NSUserDefault中吗

Button(action: {
    self.checked[index].toggle()
    UserDefaults.standard.set(self.checked, forKey: "Check")
最好的解决方案可能是使用
CoreData
,这将非常容易使用

PS:我可以稍后测试该解决方案。。现在不在我的Mac上

试试这个:(这是上次的代码;))我认为真/假设置本身不正确,但保存/加载工作正常;)

struct ChecklistView:View{
var检查表:检查表
@状态变量currentProgress:Float=0.0
@已检查状态变量:[Bool]=[false,false,false,false]
初始(检查表:检查表){
self.checklist=检查表
}
func saveUserDefaults(){
var value=“”
对于选中的每个值{
如果eachValue==true{value+=“1”}
else{value+=“0”}
}
UserDefaults.standard.set(值,forKey:checklist.title)
}
var body:一些观点{
ZStack(对齐:。引导){
//圆角转角(拐角半径:20)
//.foregroundColor(.red).不透明度(0.5)
//.框架(宽度:200)
VStack{
HStack(对齐:。顶部){
检查表.图像
.可调整大小()
.aspectRatio(内容模式:.fit)
.框架(宽度:40,高度:40)
.padding(.training)
VStack(对齐:。前导){
文本(检查表标题)
.font(.system(大小:16,重量:中等))
.padding(.bottom,4)
文本(checklist.instruction.uppercased()).font(.system(大小:12))
HStack{
ForEach(0..<检查表步骤){索引中
VStack{
按钮(操作:{
self.checked[index].toggle()
打印(自检)
self.saveUserDefaults()
}) {
ZStack{
圆角转角(拐角半径:8)
.foregroundColor(自查[索引]?颜色(“浅绿色”):.gray)
.框架(宽度:40,高度:40)
图像(系统名称:self.checked[index]?“checkmark”:“plus”)
.可调整大小()
.aspectRatio(内容模式:.fit)
.框架(宽度:16,高度:16)
.foregroundColor(自查[索引]?.white:.白色)
}
}
}
}
}
}
}.帧(宽度:350,对齐:。前导)
}
}
.onAppear(){
如果let values=UserDefaults.standard.value(forKey:self.checklist.title)作为?字符串{
self.checked=values.map{
如果$0==“1”{返回true}
返回错误
}
}
打印(自检)
}
.框架(宽度:350)
.padding(.bottom,16)
.转弯半径(8)
.padding(.top,20)
}
}
试试这个:(这是上次的代码;))我认为真/假设置本身不正确,但保存/加载工作正常;)

struct ChecklistView:View{
var检查表:检查表
@状态变量currentProgress:Float=0.0
@已检查状态变量:[Bool]=[false,false,false,false]
初始(检查表:检查表){
self.checklist=检查表
}
func saveUserDefaults(){
var value=“”
对于选中的每个值{
如果eachValue==true{value+=“1”}
else{value+=“0”}
}
UserDefaults.standard.set(值,forKey:checklist.title)
}
var body:一些观点{
ZStack(对齐:。引导){
//圆角转角(拐角半径:20)
//.foregroundColor(.red).不透明度(0.5)
//.框架(宽度:200)
VStack{
HStack(对齐:。顶部){
检查表.图像
.可调整大小()
.aspectRatio(内容模式:.fit)
.框架(宽度:40,高度:40)
.padding(.training)
VStack(对齐:。前导){
文本(检查表标题)
.font(.system(大小:16,重量:中等))
.padding(.bottom,4)
文本(checklist.instruction.uppercased()).font(.system(大小:12))
HStack{
ForEach(0..<检查表步骤){索引中
VStack{
struct ChecklistView: View {
    var checklist: Checklist
    @State var currentProgress: Float = 0.0
    @State var checked : [Bool] = [false, false, false, false]

    init(checklist: Checklist) {
        self.checklist = checklist

    }

    func saveUserDefaults() {

        var value = ""

        for eachValue in checked {
            if eachValue == true { value += "1" }
            else { value += "0" }
        }

        UserDefaults.standard.set(value, forKey: checklist.title)
    }

    var body: some View {
        ZStack(alignment: .leading) {

            //            RoundedRectangle(cornerRadius: 20)
            //                .foregroundColor(.red).opacity(0.5)
            //                .frame(width: 200)

            VStack {
                HStack(alignment: .top) {
                    checklist.image
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 40, height: 40)
                        .padding(.trailing)
                    VStack(alignment: .leading) {
                        Text(checklist.title)
                            .font(.system(size: 16, weight: .medium))
                            .padding(.bottom, 4)

                        Text(checklist.instruction.uppercased()).font(.system(size: 12))

                        HStack {
                            ForEach(0 ..< checklist.steps) { index in
                                VStack {
                                    Button(action: {
                                        self.checked[index].toggle()
                                        print(self.checked)
                                        self.saveUserDefaults()

                                    }) {
                                        ZStack {

                                            RoundedRectangle(cornerRadius: 8)
                                                .foregroundColor(self.checked[index] ? Color("LightGreen") : .gray )
                                                .frame(width: 40, height: 40)

                                            Image(systemName: self.checked[index] ?  "checkmark" : "plus")
                                                .resizable()
                                                .aspectRatio(contentMode: .fit)
                                                .frame(width: 16, height: 16)
                                                .foregroundColor(self.checked[index] ? .white : .white)

                                        }
                                    }
                                }
                            }
                        }
                    }
                }.frame(width: 350, alignment: .leading)
            }
        }
        .onAppear() {
            if let values = UserDefaults.standard.value(forKey: self.checklist.title) as? String {

                self.checked = values.map {
                    if $0 == "1" { return true }
                    return false
                }
            }
            print(self.checked)
        }
        .frame(width: 350)
        .padding(.bottom, 16)
        .cornerRadius(8)
        .padding(.top, 20)
    }
}