2016-04-22 69 views
0

如何从swift中的警报框中检索输入?我不明白为什么我的代码无法正常工作。我是一名C++程序员,所以我对swift很陌生。出于某种原因,当我到达我的印刷线时,它只是说:“添加的新样式是:”这就是全部。它不会打印出哪些用户在文本框中因故类型。这里是我的代码如何从Swift中的警报框中检索输入?

// Generate a text field for user input 
    func generateTextField() 
    { 

     //1. Create the alert controller. 
     var tempStyle = ""; 
     var alert = UIAlertController(title: "Add a New Style", message: "Enter the name of the new hairstyle below", preferredStyle: .Alert); 


     //2. Add the text field. You can configure it however you need. 
     alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in 
      textField.placeholder = "Your New Hairstyle Goes Here.."; 
     }) 

     //3. Grab the value from the text field, and print it when the user clicks OK. 
     alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in 
      let textField = alert.textFields![0] as UITextField 
      tempStyle = textField.text!; 

     })) 


     // 4. Present the alert. 
     self.presentViewController(alert, animated: true, completion: nil) 


     print("New Style Added is: " + tempStyle); 

    } 

回答

1

尝试增加print("New Style Added is: " + tempStyle)tempStyle = textField.text!。看起来打印命令没有在正确的位置被调用。所有tempStyle知道的是,它等于“”,这将解释你得到“新风格添加:”。您必须将代码添加到变量被更改的函数中,或者将var tempStyle =“”作为类变量。在这种情况下,您可以在任何函数之外添加该变量。如果要将其作为一个类的变量,则可以将print("New Style Added is: " + tempStyle)保留在原来的位置,但您需要将其设置为print("New Style Added is: " + self.tempStyle),指的是在该类(该viewController)中创建tempStyle的那个面。另外,你不需要“;”在Swift中,但我猜测这是来自Objective C的一种习惯的力量!