我正在制作一个在 SwiftUI 中使用表单的应用程序,我想使用所述表单编辑本地存储的对象。
在这种情况下,我有一个蛋糕和一个饼干要存储在内存中,我有两个结构,一个用于蛋糕,一个用于饼干。
当用户选择他/她要编辑的蛋糕或饼干时,表单字段应自动填充实际存储的可编辑蛋糕或饼干的属性。
结构是:
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)
}
}
}
}
}
}