In this example, I am able to delete the amount from the total amount using the delete button. However, I am not able to delete the load from total load. For example after entering few data for load, the total sums up in total and the individual total load amounts are shown in load1 and load2. However, while deleting one task, only the amount is subtracted from the total amount. How to subtract the deleted load amount from the total individual loads??
import SwiftUI
struct Task: Identifiable {
var id: UUID
var toDoItem: String
var amount: Float
init(toDoItem: String, amount: Float) {
self.id = UUID()
self.toDoItem = toDoItem
self.amount = amount
}
}
class TaskStore : ObservableObject {
@Published var tasks = [Task]()
}
struct Calculation: View {
@State var load1 = Float()
@State var load2 = Float()
@State var gp : Float = 0
@State var loadA : Float = 0
@State var loadB : Float = 0
@State var rate: Float = 0
@ObservedObject var taskStore = TaskStore()
@State private var birthDate = Date()
@State private var time1 = Date()
@State private var time2 = Date()
func addNewToDo() {
taskStore.tasks.append(
Task(
toDoItem: "total = \(rate.description) ",
amount: rate
)
)
}
var body: some View {
NavigationView {
VStack {
HStack {
VStack(spacing: 1) {
VStack(spacing: 1) {
List {
Section(header:Text("load 2"))
{
TextField("Enter value of load 1", value: $load1, format: .number)
TextField("Enter value of load 1", value: $load2, format: .number)
}
HStack {
Button(String(format: "Add Load"), action: {
print(Rocky(mypay: rate))
loadA += load1
loadB += load2
gp += rate
})
Button(action: {
addNewToDo()
Rocky(mypay: rate)
},
label: {
Text(" ")
})
}
ForEach(self.taskStore.tasks) { task in
Text(task.toDoItem)
}
.onMove(perform : self.move)
.onDelete(perform : self.delete) //For each
}
.navigationBarTitle("Loads")
.navigationBarItems(trailing: EditButton()) //List
Text("Total Load1 = \(loadA)")
Text("Total Load2 = \(loadB)")
Text("Total = $\(gp) ")
}.onAppear()
}
}
}
}
}
func Rocky(mypay: Float)
{
rate = load1 + load2
print("Sus \(gp)")
}
func move(from source : IndexSet, to destination : Int)
{
taskStore.tasks.move(fromOffsets: source, toOffset: destination)
}
func delete(at offsets : IndexSet) {
if let index = offsets.first {
let task = taskStore.tasks[index]
gp -= task.amount
}
taskStore.tasks.remove(atOffsets: offsets)
}
}