我在SwiftUI中无法使用动态列表。我无法使用选择器使列表动态更新

时间:2020-04-11 11:32:09

标签: ios swift swiftui

基本上如标题所述。我有一个名为“成分”的选择器,当我进入列表并单击一个元素时,它应该作为按钮(或者可能不是),然后使用add函数将该元素附加到成分列表中,该列表是一个状态变量,然后应在轮流更新底部的列表并显示其元素,但没有。我完成了其他项目,它们具有类似的更新列表的想法,但从未使用选择器。任何帮助表示赞赏。还值得一提的是,“测试”按钮适用于我想要实现的目标,而@ObservedObject可以忽略。

import SwiftUI

struct AddRecipe: View {
    @ObservedObject var recipe: RecipeFinal
    @State private var name = ""
    @State private var time = 0
    @State private var diff = ""
    @State private var ingredients = [String]()

    static var diffT = ["Easy", "Medium", "Difficult"]

    static var ingred = ["Onion","Salt","Oil","Tomato", "Garlic", 
"Peppers","Bread","Vinegar"]

    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: $name)
                Stepper(value: $time, in: 0...120, step: 15) {
                    Text("Time: \(time) minutes")
                }
                Picker ("Difficulty", selection: $diff) {
                    ForEach (AddRecipe.self.diffT, id: \.self) {
                        Text($0)
                    }
                }
                Button("TEST") {
                    self.ingredients.append("TEST")
                }
                Picker("Ingredients", selection: $ingredients) {
                    ForEach (AddRecipe.self.ingred, id: \.self) { ing in
                        Button(action: {
                            self.add(element: ing)
                        }) {
                            Text("\(ing)")
                        }
                    }
                }
                Section(header: Text("Ingredients")) {
                    List (self.ingredients, id: \.self) {
                        Text($0)
                    }
                }
            }
        }
    }
    func add (element: String) {
        self.ingredients.append(element)
    }
 }

struct AddRecipe_Previews: PreviewProvider {
    static var previews: some View {
        AddRecipe(recipe: RecipeFinal())
    }
}

0 个答案:

没有答案