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)
}
}
2
Answers
Thank you, that worked. However, what would we do in a situation if load1 and load2 were Environment variables and type Double?. Please check the below code. I have defined load1 and load2 in a different class. load1 and load2 can be called as userSettings.load1 and userSettings.load2.
You need to create 2 variables to store the data of load1 and load2 in your Task struct too, so when the delete() function execute, it knows what data to delete. I have added a few lines of code to your original code with tag //add. I have already tested it out for you too. This should work as you wanted.