ios - 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))
})
}
}
}
}
解决方案
这将是更新的代码。
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 ?? ""
推荐阅读
- node.js - model.predict.print() 未在 tensorflow.js 中显示所有结果
- javascript - 单击按钮时如何创建多个标签?当它们太多时,如何使它们消失?
- html - 如果它是一个重复的条目,它应该拒绝,如果它不是它应该插入到 sql iam 获取partyname 为 null
- c++ - 从 C++ 使用 C 库 (spglib)
- ios - 从模式页面(表单)调用时未显示 Xamarin Forms iOS UIImagePickerController
- flutter - Flutter 使用 Inherited Widget 更新状态
- unit-testing - 无法测试静态资产
- android - Android 无法通过 API 接收多条记录
- javascript - 将 Javascript 呈现的网页内容读入 R
- hadoop - 连接已经关闭 Hive