Yusha Yusha - 6 months ago 5x
Swift Question

How can I retrieve input from an alert box in Swift?

How can I retrieve input from an alert box in swift? I don't understand why my code isn't working. I'm a C++ programmer so I'm very new to swift. For some reason when I get to my print line it just says: "New Style Added is:" and that's all there is. It won't print out what the user has typed in the textbox for some reason.. Here is my code

// 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);



Try adding print("New Style Added is: " + tempStyle) tempStyle = textField.text!. It looks like the print command is not being called in the right place. All tempStyle knows is that it is equal to "", which would explain you getting "New Style Added is:". You have to add the code into the function where the variable is changed or make var tempStyle = "" a class-wide variable. In this case, you would add the variable outside of any function. If you were to make this a class-wide variable, you could leave print("New Style Added is: " + tempStyle) where it is but you would need to make it print("New Style Added is: " + self.tempStyle), referring to the face that tempStyle is created in that class (that viewController). Also, you don't need ";" in Swift, but I'm guessing it's a force of habit from Objective C!