web-dev-qa-db-fra.com

Swift: insérer une boîte d'alerte avec saisie de texte (et stocker la saisie de texte)

Dans l'un de mes viewController, je veux faire un alert box apparaît qui invite le user à taper ces informations. Ensuite, je veux que l'utilisateur stocke cette entrée à l'aide de NSUserDefaults. Comment puis-je atteindre cet objectif?

Merci d'avance!

17
l-spark

Regarde ça:

let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert)

let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
  guard let textFields = alertController.textFields,
    textFields.count > 0 else {
      // Could not find textfield
      return
  }

  let field = textFields[0]
  // store your data
  UserDefaults.standard.set(field.text, forKey: "userEmail")
  UserDefaults.standard.synchronize()
}

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

alertController.addTextField { (textField) in
  textField.placeholder = "Email"
}

alertController.addAction(confirmAction)
alertController.addAction(cancelAction)

self.present(alertController, animated: true, completion: nil)
35
Andrei Papancea

Swift

func presentAlert() {
    let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
        if let emailTextField = alertController.textFields?[0] {
            // do your stuff with emailTextField
        } 
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

    alertController.addTextField { (textField) in
        textField.placeholder = "Email"
    }

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)
}
21
Maksim Kniazev

Dans Swift

let alertController = UIAlertController(title: "SecureStyle", message: "SecureStyle AlertView.", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField) -> Void in
            textField.secureTextEntry = true
            textField.placeholder = "Password"
        }
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (result : UIAlertAction) -> Void in
            print("Cancel")
        }
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
            print(alertController.textFields?.first?.text)
        }
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
2
Sai kumar Reddy