xcode Swift UIAlertController 获取文本字段文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26305975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift UIAlertController Getting Text Field Text
提问by Henry oscannlain-miller
I need to get the text from the text fields in my alert view when the Input button is pressed.
当按下输入按钮时,我需要从警报视图中的文本字段中获取文本。
func inputMsg() {
var points = ""
var outOf = ""
var alertController = UIAlertController(title: "Input View", message: "Please Input Your Grade", preferredStyle: UIAlertControllerStyle.Alert)
let actionCancle = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel) { ACTION in
println("Cacle")
}
let actionInput = UIAlertAction(title: "Input", style: UIAlertActionStyle.Default) { ACTION in
println("Input")
println(points)
println(outOf)
}
alertController.addAction(actionCancle)
alertController.addAction(actionInput)
alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
txtField.placeholder = "I got"
txtField.keyboardType = UIKeyboardType.NumberPad
points = txtField.text
})
alertController.addTextFieldWithConfigurationHandler({(txtField: UITextField!) in
txtField.placeholder = "Out Of"
txtField.keyboardType = UIKeyboardType.NumberPad
outOf = txtField.text
})
presentViewController(alertController, animated: true, completion: nil)
}
采纳答案by matt
The UIAlertController has a textFieldsproperty. That's its text fields. Any of your handlers can examine it and thus can get the text from any of the text fields.
UIAlertController 有一个textFields属性。那是它的文本字段。您的任何处理程序都可以检查它,从而可以从任何文本字段中获取文本。
回答by Unome
As requestedhere is an implementation solution.
根据要求,这里是一个实现解决方案。
alertController.addAction(UIAlertAction(title: "Submit", style: UIAlertActionStyle.Default,handler: {
(alert: UIAlertAction!) in
if let textField = alertController.textFields?.first as? UITextField{
println(textField.text)
}
}))
As stated above, the alertController has a property called textFields. You can conditionally unwrap that property to safely access a text field if you have added one. In this case since there is only one text field I just did the unwrap using the firstproperty. Hope it helps.
如上所述, alertController 有一个名为 的属性textFields。如果您添加了一个文本字段,您可以有条件地解开该属性以安全访问文本字段。在这种情况下,因为只有一个文本字段,所以我只是使用该first属性进行了展开。希望能帮助到你。

