将对象传递到另一个视图并在SwiftUI

时间:2020-10-20 10:07:44

标签: view swiftui parameter-passing immutability

我对以下任务有疑问。我创建了一个活动结构,一个类是一个Activity对象数组。

struct Activity: Identifiable, Codable {
    var id = UUID()
    let name: String
    let description: String
    var amount: Int
}

class Activities: ObservableObject {
    @Published var activities = [Activity]() {
}

在我的主视图中,我有这些活动的列表,使用NavigationLink,我们可以转到每个活动,并查看说明和执行次数。

struct ContentView: View {
    @ObservedObject var activities = Activities()
    
    var body: some View {
        NavigationView {
            List {
                ForEach(activities.activities, content: { activity in
                    NavigationLink(
                        destination: ActivityView(activity: activity),
                        label: {
                            VStack(alignment: .leading) {
                                Text(activity.name)
                                    .font(.headline)
                                Text("\(activity.amount)")
                            }
                        })
                })
            }
        }
    }
}

我的问题是,在这个详细信息视图中,我希望能够增加执行活动的次数,但会收到一个错误:变异运算符的左侧是不可变的:'self'是不可变的

struct ActivityView: View {
    var activity: Activity
    
    var body: some View {
        Text(activity.name)
        Text(activity.description)
        Text("\(activity.amount)")
        Button(action: {
            print(activity.amount)
            self.activity.amount += 1
        }, label: {
            Text("Button")
        })
    }
}

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以像这样使用绑定

struct ActivityView: View {
    @Binding var activity: Activity
...

并更新父级以传递绑定值

    ForEach(Array(activities.activities.enumerated()), id: \.1, content: { i, activity in
        NavigationLink(
            destination: ActivityView(activity: self.$activities[i]),