-2

I have an alert controller with option buttons to set a value in a text field then call a method in the completion. The alert view pops up as normal but when a button is pressed setting the text field value is delayed and the method actual runs before the value can be set in the text field. I tried a few suggestions on here, such as using DispatchQueue.main.async but made not difference. Is there a way to delay the method call so the textfield value can be set before the method is called or a way to speed up the value being set in the textfield? Or did I miss something in my code?

//Alert message function
func alertMessage(message: String, changeLDW: Int, changeZFW: Int) {
    
    let attributedString = NSAttributedString(string: "WARNING!", attributes: [
        NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20),
        NSAttributedString.Key.foregroundColor : UIColor.red ])
    
    AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
    let alertController = UIAlertController(title: "",
                                                message: message,
                                                preferredStyle: .alert)
    alertController.setValue(attributedString, forKey: "attributedTitle")
    let cancelAction = UIAlertAction(title: "Ignore", style: .destructive, handler: nil)
    let setLDWAction = UIAlertAction(title: "Set LDW", style: .default) { (_) -> Void in
        self.maxLDWTextField.text = String(changeLDW)
        self.calculateEstimates()
        }
    let setZFWAction = UIAlertAction(title: "Set ZFW", style: .cancel)  { (_) -> Void in
        self.estimatedZFWTextField.text = String(changeZFW)
        self.calculateEstimates()
        }
    
    if changeLDW > 0 && changeZFW > 0{
        alertController.addAction(cancelAction)
        alertController.addAction(setLDWAction)
        alertController.addAction(setZFWAction)
    }
    else if changeZFW > 0 && changeLDW == 0 {
        alertController.addAction(cancelAction)
        alertController.addAction(setZFWAction)
    }
    else if changeLDW > 0 && changeZFW == 0 {
        alertController.addAction(cancelAction)
        alertController.addAction(setLDWAction)
    }
    else {
        alertController.addAction(cancelAction)
    }
    self.present(alertController, animated: true, completion: nil)
}
  • Since the buttons all call `self.calculateEstimates`, do you not think it might be useful to show us that code? Please, always try to submit your question as a [mcve]. – matt Aug 12 '20 at 01:59
  • Sorry for the late reply as I completely forgot about this. I found my problems in the self.calculateEstimates method. And I originally did't put the method code on here as it is long and at the time I did't think it was the problem. Lesson learned, thanks. – sandPitPilot Aug 27 '20 at 08:24

1 Answers1

0

why you don't add [weak self] in handler of UIAlertAction ?

goat_herd
  • 571
  • 3
  • 13