2016-04-22 66 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的一種習慣的力量!