如何解决如何在 SwiftUI 中自动填充文本字段?
我正在制作一个使用 SwiftUI 表单的应用,我想使用所述表单编辑本地存储的对象。
在本例中,我有一个蛋糕和一个 cookie 存储在内存中,我有两个结构体,一个用于蛋糕,一个用于 cookie。
当用户选择他/她想要编辑的蛋糕或饼干时,表单字段应自动填充实际存储的可编辑蛋糕或饼干的属性。
结构是:
import Foundation
struct Cake {
var name : String
var style : String
var decorations : String
}
struct Cookie{
var name : String
var style : String
}
我用于视图的代码是:
import SwiftUI
struct EditingForm: View {
@State var cake : Cake = Cake(name: "Caprese",style: "Chocolate cake made with almonds flour",decorations: "Powdered Sugar")
@State var cookie : Cookie = Cookie(name: "Chocolate Chip",style: "Cookie made with chocolate chips")
@State var group : String = "Cake"
@State var nameCake : String = ""
@State var nameCookie : String = ""
@State var styleCake : String = ""
@State var cookiesChocolateChipsType : String = ""
var body: some View {
ZStack{
Form{
Section(header: Text("Sweet Details")
){
Menu("Select the sweet you want to edit") {
Button(action: {
group = "Cake"
}) {
Text("Cake")
}.foregroundColor(.black)
Button(action: {
group = "Cookie"
}) {
Text("Cookie")
}
}
}
Section(header: Text("decorations")
){
if(group == "Cake"){
TextField("Name of the cake",text: $nameCake)
TextField("Style of the cake",text: $styleCake)
} else if (group == "Cookie"){
TextField("Name of the cookie",text: $nameCookie)
TextField("Type of chocolate chips for the cookie",text: $cookiesChocolateChipsType)
}
}
}
}
}
}
解决方法
您可以简单地使用 .onAppear() {}
修饰符。这意味着,当视图出现时,您的 @State 变量会得到更新。
在您的示例中,代码如下所示:
import SwiftUI
struct EditingForm: View {
@State var cake : Cake = Cake(name: "Caprese",style: "Chocolate cake made with almonds flour",decorations: "Powdered Sugar")
@State var cookie : Cookie = Cookie(name: "Chocolate Chip",style: "Cookie made with chocolate chips")
@State var group : String = "Cake"
@State var nameCake : String = ""
@State var nameCookie : String = ""
@State var styleCake : String = ""
@State var cookiesChocolateChipsType : String = ""
var body: some View {
ZStack{
Form{
Section(header: Text("Sweet Details")
){
Menu("Select the sweet you want to edit") {
Button(action: {
group = "Cake"
}) {
Text("Cake")
}.foregroundColor(.black)
Button(action: {
group = "Cookie"
}) {
Text("Cookie")
}
}
}
Section(header: Text("Decorations")
){
if(group == "Cake"){
TextField("Name of the cake",text: $nameCake).onAppear() {
self.nameCake = self.cake.name
}
TextField("Style of the cake",text: $styleCake).onAppear() {
self.styleCake = self.cake.style
}
} else if (group == "Cookie"){
TextField("Name of the cookie",text: $nameCookie).onAppear() {
self.nameCookie = self.cookie.name
}
TextField("Type of chocolate chips for the cookie",text: $cookiesChocolateChipsType).onAppear() {
self.cookiesChocolateChipsType = self.cookie.style
}
}
}
}
}
}
}
希望能帮助您解决问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。