0

我有一个托管对象,Treatment与另一个托管对象存在一对多关系TreatmentTime

我正在展示TreatmentTime与 a 中的给定关联的不同对象,Treatment并且ForEach我希望能够为添加和删除TreatmentTime's 设置动画。我已经尝试了很多东西,但都没有奏效。

/// this is being presented within another view
struct TreatmentView_Manual: View {
    @ObservedObject var treatment: Treatment
    var body: some View {
        ForEach(Array(zip(Array(treatment.treatmentTimes as? Set ?? Set<TreatmentTime>()).sorted { $0.time ?? Date() < $1.time ?? Date() }, treatment.wrappedTreatmentTimes.indices)), id: \.0) { (treatmentTime, index) in
            Treatment_DatePicker(treatmentTime: treatmentTime, index: index)
        }
        HStack {
            Button("Add another") {
               addTreatment()
            }
            
            Spacer()
            
            if treatment.numberOfAdmins > 1 {
                Button("Remove last"){
                    removeTreatment()
                }.foregroundColor(.red)
            }
        }
    }
    func addTreatment() {
        treatment.addToTreatmentTimes(TreatmentTime(context: treatment.managedObjectContext!))
    }
    
    func removeTreatment(_ treatmentTime: TreatmentTime) {
        // function not yet written
    }
}

struct Treatment_DatePicker: View {
    @ObservedObject var treatmentTime: TreatmentTime
    let index: Int
    var body: some View {
        DatePicker("Dose #\(index + 1)", selection: $treatmentTime.time ?? Date())
    }
}

任何建议将不胜感激。此外,如果您发现与我的代码有关的任何其他可以改进的地方,我也很想听听。

4

0 回答 0