xcode - SwiftUI:创建自己的数据类型并使用它们。如何?
问题描述
目前我正在用 SwiftUI 编写我自己的第一个应用程序。我想创建一个名为“Exercise”的自定义数据类型。为此,我创建了一个结构:
struct Exercise: Identifiable {
var id = UUID()
var name: String = ""
var description: String?
}
另外,我有一个具有不同数据的类,在其中我以数组的形式创建了该结构的实例:
var exercise: [Exercise] = []
现在我想在不同的视图中添加一个新元素到这些数组,其中我有一个用于练习名称的文本字段和一个用于描述的文本字段。但我不知道我该怎么做。有谁能够帮助我?
提前感谢,对不起我的英语:)
编辑: 使用视图代码,我想将新元素附加到具有数组“练习”的类:
var body: some View {
NavigationView {
VStack(spacing: 20){
Text("Name")
.alignmentNewExercise()
.font(.title)
TextField(placeholder, text: $newExercise)
.alignmentNewExercise()
.textFieldStyle(RoundedBorderTextFieldStyle())
TextField("Description", text: $description)
.alignmentNewExercise()
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
exercise.name = newExercise
exercise.description = description
//data.exercise.append(...) **here I want to add the new element to the array in the class "data", but I don't know how**
newExercise = ""
}) {
Text("Hinzufügen")
}
.disabled(validExercise)
Spacer()
}
.navigationBarTitle("Neue Übung")
.navigationBarItems(trailing:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Zurück")
})
}
}
带有数组的类:
class Daten: ObservableObject{
@Published var exercise: [Exercise] = []
}
解决方案
要附加新数据,您可以创建一个新数据Exercise
并将其添加到您的集合中:
let exercise = Exercise(name: self.newExercise, description: self.description)
data.exercise.append(exercise)
可以缩短为:
data.exercise.append(Exercise(name: self.newExercise, description: self.description))
Also try using plural names for your collections:
@Published var exercises: [Exercise] = []
It indicates it's a collection and not a single object.
推荐阅读
- java - @Valid 不工作 @PostMapping 春季启动
- python - JWT 中的令牌声明是什么?
- haskell - 为什么这个词法分析器不解析这个输入?
- php - 使用嵌套子PHP转换多维字符串数组
- python - Python:将 n 维矩阵/张量实现为一维元素列表
- cordova - 使用cordova-plugin-camera拍照或从图库中选择图像后重新加载cordova framework7页面
- javascript - setInterval 中的 setTimeout 不能正常工作
- java - 使用 JpaRepository SpringBoot 在两个类之间进行映射
- python - 基于来自外部对象的索引聚合组
- brightway - 找不到迁移生物圈-2-3-类别