Swift: Insert Alert Box with Text Input (and Store Text Input )

后端 未结 3 653
一个人的身影
一个人的身影 2021-02-12 23:18

In one of my viewController, I want to make an alert box appear that prompts the user to type this information.Then, I want the user to st

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-12 23:55

    Check this out:

    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)
    

提交回复
热议问题