从UIAlertView文本字段获取文本的问题

在我的应用程序,我想要一个文本框的警报。 点击“完成”后,我想将文本字段保存在一个string中。 点击“取消”后,我只想closures警报。 我已经创build了这样的警报:

var alert = UIAlertView() alert.title = "Enter Input" alert.addButtonWithTitle("Done") alert.alertViewStyle = UIAlertViewStyle.PlainTextInput alert.addButtonWithTitle("Cancel") alert.show() let textField = alert.textFieldAtIndex(0) textField!.placeholder = "Enter an Item" println(textField!.text) 

警报看起来像这样:

我的警报

我想知道如何从文本框中获取文本,以及如何为“完成”button和“取消”button创build事件。

您可以使用UIAlertController而不是UIAlertView。

我已经使用UIAlertController实现并testing了您真正想要的内容。 请尝试下面的代码

  var tField: UITextField! func configurationTextField(textField: UITextField!) { print("generating the TextField") textField.placeholder = "Enter an item" tField = textField } func handleCancel(alertView: UIAlertAction!) { print("Cancelled !!") } var alert = UIAlertController(title: "Enter Input", message: "", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(configurationTextField) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:handleCancel)) alert.addAction(UIAlertAction(title: "Done", style: .Default, handler:{ (UIAlertAction) in print("Done !!") print("Item : \(self.tField.text)") })) self.presentViewController(alert, animated: true, completion: { print("completion block") }) 

你将不得不实施UIAlertViewDelegate的

 optional func alertView(_ alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) 

对于SWIFT 3

 @IBAction func ForgotPassword(_ sender: Any) { let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert) let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in if let field = alertController.textFields![0] as? UITextField { // store and use entered data } else { print("please enter email id") } } 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) } 

我希望它会帮助别人:)

对于iOS 8+,您应该使用UIAlertController而不是UIAlertView。 为了支持iOS 7,你应该实现(UIAlertViewDelegate):

 func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { //... let textField = alertView.textFieldAtIndex(0) }