本文介绍了从 Swift 中的 iOS 警报中的 TextField 获取输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用输入生成警报消息,然后从输入中获取值.我发现了很多很好的教程如何制作输入文本字段.但我无法从警报中获取值.
I'm trying to make an alert message with input, and then get the value from the input. I've found many good tutorials how to make the input text field. but I can't get the value from the alert.
推荐答案针对 Swift 3 及更高版本更新:
Updated for Swift 3 and above:
//1. Create the alert controller. let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert) //2. Add the text field. You can configure it however you need. alert.addTextField { (textField) in textField.text = "Some default 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("Text field: (textField.text)") })) // 4. Present the alert. self.present(alert, animated: true, completion: nil)斯威夫特 2.x
Swift 2.x
假设您想在 iOS 上收到操作提醒:
Assuming you want an action alert on iOS:
//1. Create the alert controller. var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert) //2. Add the text field. You can configure it however you need. alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in textField.text = "Some default 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] (action) -> Void in let textField = alert.textFields![0] as UITextField println("Text field: (textField.text)") })) // 4. Present the alert. self.presentViewController(alert, animated: true, completion: nil)更多推荐
从 Swift 中的 iOS 警报中的 TextField 获取输入值
发布评论