What's a simple way to get a text input popup dialog box on an iPhone

Viewed 160031

I want to get the user name. A simple text input dialog box. Any simple way to do this?

13 Answers

Final output when you call the function below

For Swift 5.1: (updating previous answer)

func doAlertControllerDemo() {
        
        var inputTextField: UITextField?;
    let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your password.", preferredStyle: UIAlertController.Style.alert);
    
    passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)
        
        let entryStr : String = (inputTextField?.text)! ;
        
        print("BOOM! I received '\(entryStr)'");
        
        self.doAlertControllerDemo(); //do again!
    }));
    
    passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: { (action) -> Void in
        print("done");
    }));
    
    passwordPrompt.addTextField(configurationHandler: {(textField: UITextField!) in
        textField.placeholder = "Password"
        textField.isSecureTextEntry = false       /* true here for pswd entry */
        inputTextField = textField
    });
    
    self.present(passwordPrompt, animated: true, completion: nil);
    return;
}

Building on John Riselvato's answer, to retrieve the string back from the UIAlertView...

alert.addAction(UIAlertAction(title: "Submit", style: UIAlertAction.Style.default) { (action : UIAlertAction) in
            guard let message = alert.textFields?.first?.text else {
                return
            }
            // Text Field Response Handling Here
        })
Related