简体   繁体   English

如何从警报文本字段中的用户输入获取字符串

[英]how to get the string from user input in alert textfield

i am trying to get a string from user input textfield in an alert like that, but I always get nil value. 我试图在这样的警报中从用户输入文本字段中获取字符串,但是我总是得到nil值。 the code i use to show that alert textfield is like this 我用来显示警报文本字段的代码是这样的

 @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
        // show an alert to show up a quick textfield


        var textField = UITextField()
        let itemTitle = textField.text!

        print("the title is \(itemTitle) ....")


        let alert = UIAlertController(title: "Add Item to your to do list", message: "", preferredStyle: .alert)
        let addItemAction = UIAlertAction(title: "Add item", style: .default) { (action) in
            // after user click "add item", the new item will be displayed to table view

            let newItem = Item()
            newItem.title = itemTitle


            self.itemArray.append(newItem)
            self.saveItems()


        }


        alert.addTextField { (alertTextfield) in
            alertTextfield.placeholder = "Create a new item"
            textField = alertTextfield
            // store a data from user to 'textField' variable, so it can be accessed in closure at 'addItemAction'
        }



        alert.addAction(addItemAction)
        present(alert, animated: true, completion: nil)

    }

My UI 我的UI

在此处输入图片说明

I am trying to print the itemTitle , but i never get the string from the user. 我正在尝试打印itemTitle ,但是我从未从用户那里得到字符串。 like this 像这样

Output 输出量

在此处输入图片说明

what went wrong in here? 这里出了什么问题?

You will get that once user pressed Add item not before that where you are trying to print it. 一旦用户按下Add item ,您将在尝试打印该Add item之前获得该消息。

check below code: 检查以下代码:

let addItemAction = UIAlertAction(title: "Add item", style: .default) { (action) in

    // after user click "add item", the new item will be displayed to table view
    print(textField.text)  //Here you will get user text.

    let newItem = Item()
    newItem.title = textField.text //add it here
    self.itemArray.append(newItem)
    self.saveItems()   
}

You have to get the text from textField when Add Item is pressed. 按下Add Item时,您必须从textField中获取文本。

Change this 改变这个

newItem.title = itemTitle

to

newItem.title = textField.text

Try this 尝试这个

   /// define alert controller 
  let alert = UIAlertController(title: "Alert Title",
                          message: "Alert message",
                          preferredStyle: UIAlertControllerStyle.alert)

 /// add OK Action
  let ok = UIAlertAction(title: "OK",
                   style: UIAlertActionStyle.default) { (action: UIAlertAction) in

    /// get the textfield instance form textFields array

                    if let alertTextField = alert.textFields?.first, alertTextField.text != nil {

                        print("And the text is... \(alertTextField.text!)!")

                    }


  }

     /// add CANCEL Action

   let cancel = UIAlertAction(title: "Cancel",
                       style: UIAlertActionStyle.cancel,
                       handler: nil)

    /// add first textfeild to the alertController
    alert.addTextField { (textField: UITextField) in

    /// configure textfeild with properties like placeholder and textColor
    textField.placeholder = "Text here"

 }

/// add actions to the alertController

alert.addAction(ok)
alert.addAction(cancel)

/// present alertController in current viewController

self.present(alert, animated: true, completion: nil)

first of all, let itemTitle = textField.text! 首先, let itemTitle = textField.text! will make the itemTitle only assigned once and it will contain empty string as your textField doesn't have any value yet, thats why when you printed it out, it does not return any string. 将使itemTitle仅分配一次,并且将包含空字符串,因为您的textField还没有任何值,这就是为什么当您打印出来时,它不返回任何字符串。

if you want a messy way to do it, you could keep your code but delete 如果您想采用一种凌乱的方法,可以保留您的代码,但删除

let itemTitle = textField.text! 

and do what @Bilal said 并做@Bilal所说的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM