首页 > 解决方案 > 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] = []
 }

标签: xcodestructswiftui

解决方案


要附加新数据,您可以创建一个新数据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.


推荐阅读