首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Swift中从iOS警报中的TextField获取输入值

问在Swift中从iOS警报中的TextField获取输入值
EN

Stack Overflow用户
提问于 2014-10-26 05:27:26
回答 2查看 117.1K关注 0票数 140

我正在尝试使用输入生成一条警告消息,然后从输入中获取值。我找到了很多关于如何创建输入文本字段的好教程。但我无法从警报中获取值。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-26 05:34:35

针对Swift 3及更高版本进行了更新:

代码语言:javascript
复制
//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)

Swift 2.x

假设您想要iOS上的操作警报:

代码语言:javascript
复制
//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)
票数 372
EN

Stack Overflow用户

发布于 2021-08-31 02:26:00

Swift版本: 5.+

在当前作用域中创建一个新的TextField变量,并将其分配给alert.addTextField完成处理程序中的alertTextField。在UIAlertAction完成处理程序中使用textField的值。

代码语言:javascript
复制
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
          //Variable to store alertTextField
            var textField = UITextField()
            
            let alert = UIAlertController(title: "Add new item", message: "", preferredStyle: .alert)
            alert.addTextField { alertTextField in
                alertTextField.placeholder = "Create new item"
                
                //Copy alertTextField in local variable to use in current block of code
                textField = alertTextField
            }
            
            let action = UIAlertAction(title: "Add item", style: .default) { action in
                //Prints the alertTextField's value
                print(textField.text!)
            }
            
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        }
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26567413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档