Swift 如何在视图中更新结构的值
在SwiftUI中,我有一个要保存视图数据的结构。假设有一个视图,用户可以在其中创建配方。它有一个文本字段来键入配方名称,还有一些选项可以选择并添加到结构属性中的数组中 我成功地创建了结构并在视图中引入它,但我无法更改它的值。结构的值应该根据用户对视图所做的操作以及添加到视图中的信息进行更新。 我提出了一个简单的观点,即在TextField中输入的任何内容都将添加到结构的一个属性中。 对于下面的代码,我无法将其分配给属性:“self”是不可变的Swift 如何在视图中更新结构的值,swift,struct,swiftui,swift-structs,swift-class,Swift,Struct,Swiftui,Swift Structs,Swift Class,在SwiftUI中,我有一个要保存视图数据的结构。假设有一个视图,用户可以在其中创建配方。它有一个文本字段来键入配方名称,还有一些选项可以选择并添加到结构属性中的数组中 我成功地创建了结构并在视图中引入它,但我无法更改它的值。结构的值应该根据用户对视图所做的操作以及添加到视图中的信息进行更新。 我提出了一个简单的观点,即在TextField中输入的任何内容都将添加到结构的一个属性中。 对于下面的代码,我无法将其分配给属性:“self”是不可变的 struct Recipe: Codable {
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
}
视图:
知道如何解决这个问题吗?这样我就可以与结构交互并更新其属性。我还将在其他视图中使用此结构变量
提前感谢添加
@State
@State var recipe = Recipe(..
另外,在使用
recipe
内部按钮操作之前,不要忘记添加self.
。添加@State
@State var recipe = Recipe(..
另外,在使用
recipe
内部按钮操作之前,不要忘记添加self.
。对于提供的用例,最合适的方法是使用视图模型,如下例所示
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")
}
}
}
}
对于提供的用例,最合适的方法是使用视图模型,如下例所示
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")
}
}
}
}
这是伟大的,我将标记它作为答案。谢谢但是,您能否解释一下如何在另一个视图中访问
recipeVM
中的数据?@Danny,recipeVM是一个引用,因此您可以通过构造函数或作为环境对象,或作为其他引用类型对象的成员,将其注入另一个视图。这很好,我将其标记为应答。谢谢但是,您能否解释如何在另一个视图中访问recipeVM
中的数据?@Danny,recipeVM是一个引用,因此您可以通过构造函数或作为环境对象,或作为其他引用类型对象的成员,将其注入另一个视图。