首页 > 解决方案 > UserDefaults 文本/SwiftUI

问题描述

当我单击“更新”按钮时,我希望文本视图保存用户默认值中使用的文本。
我不能。你知道如何?可以编辑代码吗?更新后,我希望复选框出现,但首先我需要设置用户默认值。

Struct ContentView: View{
@State private var profilName = ""
@State private var profilSurname = ""

var body: some View{

 ZStack{ 

 VStack{  
            TextField("Name", text: $profilName)
                .frame(height: 60)
                .padding([.leading, .trailing], 20)
                .foregroundColor(.white)
                .font(Font.system(size: 30, design: .default))
                .multilineTextAlignment(.center)
                .accentColor(Color.white)
                .overlay(RoundedRectangle(cornerRadius:30)
                            .stroke(Color(#colorLiteral(red: 0.5411764706, green: 
0.4549019608, blue: 0.2823529412, alpha: 1)), lineWidth: 1)).padding(.horizontal, 50)

               TextField("Surname", text: $profilSurname)
                        .frame(height: 60)
                        .padding([.leading, .trailing], 20)
                        .foregroundColor(.white)
                        .font(Font.system(size: 30, design: .default))
                        .multilineTextAlignment(.center)
                        .accentColor(Color.white)
                        .overlay(RoundedRectangle(cornerRadius:30)
                                    .stroke(Color(#colorLiteral(red: 0.5411764706, green: 0.4549019608, blue: 0.2823529412, alpha: 1)), lineWidth: 1)).padding(.horizontal, 50)

 Button(action: {
             
            }, label: {
                Text("Update")
                    .frame(width:300 , height: 40)
                    .padding(10)
                    .font(Font.system(size: 30, weight: .medium, design: .serif))
                    .foregroundColor(.white)
                    .background(RoundedRectangle(cornerRadius: 45))
                    .foregroundColor(.init(red: 45 / 255, green: 0 / 255, blue: 112 / 255))

            })
}
}
}
}

在此处输入图像描述

标签: iosswiftswiftui

解决方案


这将是更新的代码。

Button(action: {
         // This is the action section. You can add your code here
         UserDefaults.standard.set($profilSurname.wrappedValue, forKey: "surnname")
        }, label: {
            Text("Update")
                .frame(width:300 , height: 40)
                .padding(10)
                .font(Font.system(size: 30, weight: .medium, design: .serif))
                .foregroundColor(.white)
                .background(RoundedRectangle(cornerRadius: 45))
                .foregroundColor(.init(red: 45 / 255, green: 0 / 255, blue: 112 / 255))

        })

从 Userdefaults 获取存储的值

let surnName = UserDefaults.standard.object(forKey: "surnname") as? String ?? ""  

推荐阅读