抱歉,如果我的问题很愚蠢,我是编程的初学者。我有一个从我的视图模型数组生成的列表中指向详细视图的导航链接。在详细视图中,我希望能够改变点击元素的属性之一,但我似乎无法弄清楚如何做到这一点。我不认为我解释得很好,所以这里是代码。
// model
struct Activity: Identifiable {
var id = UUID()
var name: String
var completeDescription: String
var completions: Int = 0
}
// view model
class ActivityViewModel: ObservableObject {
@Published var activities: [Activity] = []
}
// view
struct ActivityView: View {
@StateObject var viewModel = ActivityViewModel()
@State private var showingAddEditActivityView = false
var body: some View {
NavigationView {
VStack {
List {
ForEach(viewModel.activities, id: \.id) {
activity in
NavigationLink(destination: ActivityDetailView(activity: activity, viewModel: self.viewModel)) {
HStack {
VStack {
Text(activity.name)
Text(activity.miniDescription)
}
Text("\(activity.completions)")
}
}
}
}
}
.navigationBarItems(trailing: Button("Add new"){
self.showingAddEditActivityView.toggle()
})
.navigationTitle(Text("Activity List"))
}
.sheet(isPresented: $showingAddEditActivityView) {
AddEditActivityView(copyViewModel: self.viewModel)
}
}
}
// detail view
struct ActivityDetailView: View {
@State var activity: Activity
@ObservedObject var viewModel: ActivityViewModel
var body: some View {
VStack {
Text("Number of times completed: \(activity.completions)")
Button("Increment completion count"){
activity.completions += 1
updateCompletionCount()
}
Text("\(activity.completeDescription)")
}
}
func updateCompletionCount() {
var tempActivity = viewModel.activities.first{ activity in activity.id == self.activity.id
}!
tempActivity.completions += 1
}
}
// Add new activity view (doesn't have anything to do with question)
struct AddEditActivityView: View {
@ObservedObject var copyViewModel : ActivityViewModel
@State private var activityName: String = ""
@State private var description: String = ""
var body: some View {
VStack {
TextField("Enter an activity", text: $activityName)
TextField("Enter an activity description", text: $description)
Button("Save"){
// I want this to be outside of my view
saveActivity()
}
}
}
func saveActivity() {
copyViewModel.activities.append(Activity(name: self.activityName, completeDescription: self.description))
print(copyViewModel.activities)
}
}
在详细视图中,我正在尝试更新该特定活动的完成计数,并让它更新我的视图模型。我上面尝试的方法可能没有意义,显然不起作用。我只是把它留下来展示我的尝试。
感谢您提供任何帮助或见解。