如何让UIAlertController等待用户交互



我有一个IBAction按钮,可以进行计算。在这个IBAction中,我想实现一个UIAlertController按钮,其中用户可以按下";OK";或";取消";以确认重新计算
问题是,只要按下IBAction按钮,计算就完成了。

如何使函数等待UIAlertController响应。

@IBAction func buttonCalculate(_ sender: UIButton) {

let startDate = datePickerStart.date
let endDate = datePikcerEnd.date
// 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")}

alertController.addAction(defaultAction)
alertController.addAction(cancelAction)
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 = "-"
}
}

您需要放入IBAction"ok"回调、要重新计算的代码(或调用重新计算的函数(。

就像这样,只有当用户点击ok时才进行重新计算

最新更新