How to make UIAlert waiting for user interaction?

Hi guys,

I'm quiet new to coding and hope to get support from you.

I have a IBAction button which makes a calculation. In this IBAction, I want to implement an UIAlertController where the user can press "OK" or "Cancel" to confirm a recalculation. The Problem is that asap IBAction button is pressed, the calculation is done. How can I make the function wait for UIAlertController response.

@IBAction func buttonCalculate(_ sender: UIButton) {

    let startDate =
    let endDate =
    // Calculate DAYS between start and end date
    var diff = Calendar.current.dateComponents([.day], from: startDate, to: endDate).day!
    //calculate ALL between start and end date
    var daily = 6
    diff += 1
    daily = daily*diff
    // If "Calculate" button is pressed for recalculationhen 

        let emptyDiffCalcDaysLabel = diffCalcDaysLabel.text
        let emptyAmountLabel = allAmount.text
        if emptyDiffCalcDaysLabel != "-"  || emptyAmountLabel != "-"
            let alertController = UIAlertController(title: "Attention", message: "Everything will be recalculated", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "Ok", style: .default) {(ACTION) in print("OK")}
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) {(ACTION) in print("Cancel")}
            self.present(alertController, animated: true)
    //Alert when negative value is calculated
    if diff < 1
        let negativeDaysUIAlert = UIAlertController(title: "Attention", message: "Entered Date is invalid!", preferredStyle: .alert)
        negativeDaysUIAlert.addAction(UIAlertAction(title: "OK", style: .default))
        self.present(negativeDaysUIAlert, animated: true, completion: nil)
        // Show "-" instead of negative value
        diffCalcDaysLabel.text = "-"
        allAmount.text = "-"

You need to trigger the calculation from the handler of the alert button which indicates the user wishes to perform it (The "OK" action).

Many thanks for reply.
This means I need to move the IBAction to the action like this:

let defaultAction = UIAlertAction(title: "Ok", style: .default) {(ACTION) in HERE SHOULD BE THE IBACTION CODE}

Is that correct?


1 Like