gpt4 book ai didi

swift - 如何更新 View 中结构的值

转载 作者:行者123 更新时间:2023-12-02 19:29:59 26 4
gpt4 key购买 nike

在 SwiftUI 中,我有一个想要保存 View 数据的结构。假设有一个 View ,用户可以在其中创建菜谱。它有一个用于输入配方名称的文本字段,以及用于选择并添加到结构属性中的数组的选项。

我设法制作了该结构并将其引入 View 中,但我无法更改它的值。结构的值应根据用户在 View 上执行的操作以及他们添加到其中的信息进行更新。我制作了一个简单的 View ,在 TextField 中输入的任何内容都将添加到该结构的属性之一中。对于下面的代码,我得到 Cannot allocate to property: 'self' is immutable

struct Recipe: Codable {
let user: Int
var recipeName, createdDate: String
let ingredients: [Ingredient]
let equipment: [[Int]]

enum CodingKeys: String, CodingKey {
case user = "User"
case recipeName = "RecipeName"
case createdDate
case ingredients = "Ingredients"
case equipment = "Equipment"
}
}

struct Ingredient: Codable {
let ingredient, size: Int
}

查看:

struct ContentView: View {
var recipe = Recipe(user: 1231, recipeName: "Recipe Name", createdDate: "SomeDate", ingredients: [Ingredient(ingredient: 1, size: 2)], equipment: [[1],[4],[5]])


var body: some View {
VStack {
Text(self.recipe.recipeName)
Button(action: {
recipe.recipeName = "New Name" //Cannot assign to property: 'self' is immutable
}) {
Text("Change Name")
}
}
}
}

知道如何解决这个问题,以便我可以与结构交互并更新其属性。我也会在其他 View 中使用这个结构变量。

提前致谢

最佳答案

对于所提供的用例,最合适的是使用 View 模型,如下例所示

class RecipeViewModel: ObservableObject {
@Published var recipe: Recipe
init(_ recipe: Recipe) {
self.recipe = recipe
}
}

所以在 View 中

struct ContentView: View {
@ObservedObject var recipeVM = RecipeViewModel(Recipe(user: 1231, recipeName: "Recipe Name", createdDate: "SomeDate", ingredients: [Ingredient(ingredient: 1, size: 2)], equipment: [[1],[4],[5]]))


var body: some View {
VStack {
Text(self.recipeVM.recipe.recipeName)
Button(action: {
self.recipeVM.recipe.recipeName = "New Name"
}) {
Text("Change Name")
}
}
}
}

关于swift - 如何更新 View 中结构的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61977451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com