Search code examples
iosswiftuialertcontrolleruiactionsheet

How to not add UIAlertAction to UIActionSheet if it has already been added


I'm adding a UIAlertAction with the following code:

    @IBAction func doneButtonTapped(_ sender: Any) {
        
        self.present(lastInstructionAlert, animated: true, completion: nil)
        
        lastInstructionAlert.addAction(UIAlertAction(title: "Back", style: .default, handler: { (action) in
            print("Go Back")
            return
        }))
        
        lastInstructionAlert.addAction(UIAlertAction(title: "Home", style: .default, handler: { (action) in
            print("Go Home")
            self.present(self.mealPlanViewController, animated: true, completion: nil)
        }))
        
    }

The issue is that when the user presses "Back" and then "Done" again, it adds the UIAlertActions again resulting in duplicates.

enter image description here

How can I prevent those UIAlertActions from being added again if they were already added before?


Solution

  • As you make lastInstructionAlert an instance variable every time you click the action doneButtonTapped new alert actions are added , so make it local

    @IBAction func doneButtonTapped(_ sender: Any) {
        
       let lastInstructionAlert = UIAlertController(title: "Well done,chef!", message: "It's time to eat", preferredStyle: .alert)
    
        lastInstructionAlert.addAction(UIAlertAction(title: "Back", style: .default, handler: { (action) in
            print("Go Back")
            return
        }))
        
        lastInstructionAlert.addAction(UIAlertAction(title: "Home", style: .default, handler: { (action) in
            print("Go Home")
            self.present(self.mealPlanViewController, animated: true, completion: nil)
        }))
         
        self.present(lastInstructionAlert, animated: true, completion: nil)
    }
    

    Or move adding the alert actions say to viewDidLoad