Reputation: 13
I'm new to Swift so I'm not sure this is possible; but I have some code where each food type is worth a value in kgs. I use increment buttons to select how many of each food type is selected and display this tally with the countLabel. Then the value in kgs is added to a currentTotal of all the foods combined. This current total is delegated to another class/storyboard. I've checked and my delegation and tally is working. But the currentTotal is not. Basically the currentTotal is staying within each case type e.g if I increment watermelon by 2 and watermelon is 10kg each, the currentTotal is 20kg. If I switch types (tap the increment buttons of another food type), the currentTotal begins at 0 and will do a currentTotal for that type e.g water is worth 2kg. If I tap the increment button twice the waterTally equals 2 and the currentTotal displays now as 4kg. If I switch back to watermelon the currentTotal is 20kg again (so each type's currentTotal is persistent). But I want the currentTotal to equal the total of ALL the types, together, not just be the currentTotal of each type separately. I tried changing currentTotal in each case to the type total i.e "waterTotal", then wrote currentTotal = waterTotal + carrotTotal + watermelonTotal + avocadoTotal
outside the cases (I added it inside the function directly above delegate?.showTotal(currentTotal)
but that had the same outcome as stated above. Is it just not possible to add values of different switch cases or is there some way to do this? Below is is the class I'm referring to and the delegate object class. Thanks
Apologies, I was asked to remove the code as it will be committed to a private repo.
Upvotes: 0
Views: 86
Reputation: 52013
You create a new view for each type
for type in incrementTypes {
let nib = UINib(nibName: "WildlifeIncrementer", bundle: nil).instantiate(withOwner: self, options: nil)
This means that each type will have its own currentTotal
so when you call showTotal
only the value from the last view is included in the currentTotal
in WildlifeCalculatorViewController
Now the first answer would be to change showTotal
to
func showTotal(_ total: Int) {
currentTotal += total
totalLabel.text = ("\(currentTotal)kg")
}
but then you need to call it separately when adding and removing items (and you need to allow it to be negative).
The better solution is to re-design your implementation of the view class and the delegate pattern, do you want one view per type or one view for all? You might also be better of with a separate class for holding count/weight data and doing the calculations.
Upvotes: 1