How can I have the label text revert to original cost when alert controller is dismissed

70 Views Asked by At

So my goal is to have the label text always revert back to the original price if the alert view controller is dismissed.

Here is a clip of the issue so you guys can understand it more, it would be too long to explain over text...

Bug gif

So as you can see, when the user cancels the alert prompt, I want everything to revert back as if they never pressed it in the first place. The stepper value reverts, the number label text reverts, but the event cost does not and I can't figure out why.

Here is the @IBAction function I use with the stepper:

 @IBAction func guestsCount(_ sender: UIStepper) {
    
    guestNumberCount.text = String(Int(sender.value))

    
    let totalCost = Decimal(sender.value) * cost
    
    let formatted = totalCost.formattedAmount
    
    
    
    var textfield = UITextField()
    var textfield2 = UITextField()
   
    actualCostOfEvent.text = "$\(formatted ?? "")"

           if(Int(sender.value) > sampleStepperValueForIncrement){
               print("increasing")
               sampleStepperValueForIncrement += 1
            let alert = UIAlertController(title: "Add A Guest", message: "Type full name the of guest you want to add below", preferredStyle: .alert)
            let addGuest = UIAlertAction(title: "Add", style: .default) { (add) in
                guard let user = Auth.auth().currentUser else { return }
                db.document("student_users/\(user.uid)/guestTickets/guestDetails").setData(["guests": FieldValue.arrayUnion([textfield.text ?? "Nil"])], merge: true) { (error) in
                    if let error = error {
                        print("There was an error adding the name: \(error)")
                    } else {
                        print("name added successfully")
                    }
                }
                
            }
            let dismiss = UIAlertAction(title: "Dismiss", style: .cancel) { (cancel) in
                self.dismiss(animated: true, completion: nil)
                self.guestNumberCount.text = String(Int(sender.value) - 1)
                self.stepperValue.value -= 1

                
            }
            alert.addTextField { (alerttextfield) in
                textfield = alerttextfield
                alerttextfield.placeholder = "Guest Name"
                alerttextfield.clearButtonMode = .whileEditing
            }
            
            alert.addAction(dismiss)
            alert.addAction(addGuest)
            present(alert, animated: true, completion: nil)

           }
           else {
               print("decreasing")
               sampleStepperValueForIncrement =  sampleStepperValueForIncrement - 1
            let alert = UIAlertController(title: "Remove A Guest", message: "Type the full name of the guest you want to remove. The guest name is case-sensitive and must equal the name you added.", preferredStyle: .alert)
            let dismiss = UIAlertAction(title: "Dismiss", style: .cancel) { (cancel) in
                self.dismiss(animated: true, completion: nil)
                self.guestNumberCount.text = String(Int(sender.value) + 1)
                self.stepperValue.value += 1

            }
            let removeGuest = UIAlertAction(title: "Remove", style: .destructive) { (remove) in
                guard let user = Auth.auth().currentUser else { return }
                db.document("student_users/\(user.uid)/guestTickets/guestDetails").updateData(["guests": FieldValue.arrayRemove([textfield2.text ?? "Nil"])]) { (error) in
                    if let error = error {
                        print("There was an error removing the name: \(error)")
                    } else {
                        print("name removed successfully")
                    }
                }
                
            }
            
            
            alert.addTextField { (alerttextfield2) in
                textfield2 = alerttextfield2
                alerttextfield2.placeholder = "Guest Name"
                alerttextfield2.clearButtonMode = .whileEditing
            }
            
            alert.addAction(dismiss)
            alert.addAction(removeGuest)
            present(alert, animated: true, completion: nil)
           }
    
 
    
}

The problems both stem from the dismiss actions in both the if statement and the else statement. I tried possibly adding Decimal(sender.value) - 1 in one dismiss action and then Decimal(sender.value) + 1 in the other, but those didn't make a difference. The exact thing happens when you already have a guest added and you decide to remove, but end up dismissing the alert vc, the price also doesn't revert as well. The odd thing is that if I add all the way to the max value, which is 6 and then remove guests all the way back down to 1 again, the price will revert back to the original price.

Any help would be appreciated, thanks.

2

There are 2 best solutions below

1
jnpdx On

You only set actualCostOfEvent.text before the alert controller is displayed.

In the event that it is cancelled, you'll need to set it again, with the recalculated value once you've decremented the stepper again.

I'd suggest moving that code into a helper function so that you aren't repeating it:

func setLabelToFormattedTotalCost(multiplier: Int) {
  let totalCost = Decimal(multiplier) * cost
  let formatted = totalCost.formattedAmount
  actualCostOfEvent.text = "$\(formatted ?? "")"
}

Then, call that with the stepper value (that would be the multiplier parameter) at the beginning of guestsCount and then again once you've decremented the value if the alert is dismissed.

2
Sandeep Bhandari On

Its because in dismiss you reset stepper value and guest number count but dont update the cost value, so in both dismiss action you can have

        let dismiss = UIAlertAction(title: "Dismiss", style: .cancel) { (cancel) in
        
            //all other code of yours and finally 
 
            let totalCost = Decimal(self.stepperValue.value) * cost
            let formatted = totalCost.formattedAmount
            actualCostOfEvent.text = "$\(formatted ?? "")"
        }

You can obviously move this to a function and call the function from both dismiss action as

    func updateCostValue() {
        let totalCost = Decimal(self.stepperValue.value) * cost
        let formatted = totalCost.formattedAmount
        actualCostOfEvent.text = "$\(formatted ?? "")"
    }
            let dismiss = UIAlertAction(title: "Dismiss", style: .cancel) { (cancel) in
                self.dismiss(animated: true, completion: nil)
                self.guestNumberCount.text = String(Int(sender.value) - 1)
                self.stepperValue.value -= 1

                self.updateCostValue()
            }
let dismiss = UIAlertAction(title: "Dismiss", style: .cancel) { (cancel) in
                self.dismiss(animated: true, completion: nil)
                self.guestNumberCount.text = String(Int(sender.value) + 1)
                self.stepperValue.value += 1

                self.updateCostValue()
            }