FA95
FA95

Reputation: 43

Display an alert within an alert

I am trying to display an alert that takes user input and then pops up the text that has been given

@IBAction func forgotPassword(_ sender: Any) {
    //1. Create the alert controller.
    let alert = UIAlertController(title: "Email Recovery", message: "Enter your email to recover your account", preferredStyle: .alert)

    //2. Add the text field. You can configure it however you need.
    alert.addTextField { (textField) in
        textField.text = ""
    }

    // 3. Grab the value from the text field, and print it when the user clicks OK.
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
        let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
        print("An email has been sent to \(String(describing: textField?.text)) for account recovery")
    }))

    // 4. Present the alert.
    self.present(alert, animated: true, completion: nil)
}

The input works fine as well the output although instead of giving another alert, it just prints what I need in the console.

Am I missing something?

Upvotes: 1

Views: 1712

Answers (1)

mugx
mugx

Reputation: 10105

I guess you misunderstood a bit: "print" is just printing on your console, if you want to open a new alert after touching on the "ok" button, you may want to complete your code with:

alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert, weak self] (_) in
  let message = "An email has been sent to \(alert?.textFields?.first?.text ?? "") for account recovery"
  let innerAlert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
  innerAlert.addAction(UIAlertAction(title: "OK", style: .default, handler:nil))
  self?.present(innerAlert, animated: true, completion: nil)
}))

Upvotes: 4

Related Questions