如何更新视图中结构的值 [英] How to update the values of a struct in a View

查看:31
本文介绍了如何更新视图中结构的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In SwiftUI I have a struct that want to hold data of the View. Let's say there is a View that user can create a recipe in it. It has a text field to type the recipe name, and options to choose and add to the array in the struct's properties.

我设法制作了结构并将其引入到视图中,但我无法更改它的值.结构的值应该根据用户在视图上所做的事情以及他们添加到其中的信息进行更新.我做了一个简单的视图,在 TextField 中输入的任何内容都将添加到结构的属性之一中.对于下面的代码,我得到了无法分配给属性:'self' 是不可变的

I managed to make the struct and introduce it in the View but I cannot change it values. The values of the struct should be updated based on what users does on the View and the info they add to it. I made a simple View that whatever is entered in the TextField will be added in one of the properties of the struct. For the below code I get Cannot assign 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")
            }
        }
    }
}

任何想法如何解决这个问题,以便我可以与结构交互并更新其属性.我也会在其他视图中使用这个结构体变量.

Any idea how to solve this so I can interact with the struct and update its properties. I will use this struct variable in other Views as well.

提前致谢

推荐答案

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

For the use-case as provided the most appropriate is to use view model as in example below

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

如此看来

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")
            }
        }
    }
}

这篇关于如何更新视图中结构的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆