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

13

132

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

Gnawing answered 12/6, 2011 at 0:41 Comment(1)
just wait a few months, till about september, and you life will be a lot easier.Joost
B
265

In iOS 5 there is a new and easy way to this. I'm not sure if the implementation is fully complete yet as it's not a gracious as, say, a UITableViewCell, but it should definitly do the trick as it is now standard supported in the iOS API. You will not need a private API for this.

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"This is an example alert!" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
[alert release];

This renders an alertView like this (screenshot taken from the iPhone 5.0 simulator in XCode 4.2):

example alert with alertViewStyle set to UIAlertViewStylePlainTextInput

When pressing any buttons, the regular delegate methods will be called and you can extract the textInput there like so:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    NSLog(@"Entered: %@",[[alertView textFieldAtIndex:0] text]);
}

Here I just NSLog the results that were entered. In production code, you should probably keep a pointer to your alertView as a global variable or use the alertView tag to check if the delegate function was called by the appropriate UIAlertView but for this example this should be okay.

You should check out the UIAlertView API and you'll see there are some more styles defined.

Hope this helped!

-- EDIT --

I was playing around with the alertView a little and I suppose it needs no announcement that it's perfectly possible to edit the textField as desired: you can create a reference to the UITextField and edit it as normal (programmatically). Doing this I constructed an alertView as you specified in your original question. Better late than never, right :-)?

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Please enter your name:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeNumberPad;
alertTextField.placeholder = @"Enter your name";
[alert show];
[alert release];

This produces this alert:

UIAlertView that uses the UIAlertViewPlainTextInput alertStyle to ask a user name

You can use the same delegate method as I poster earlier to process the result from the input. I'm not sure if you can prevent the UIAlertView from dismissing though (there is no shouldDismiss delegate function AFAIK) so I suppose if the user input is invalid, you have to put up a new alert (or just reshow this one) until correct input was entered.

Have fun!

Berkey answered 21/11, 2011 at 20:0 Comment(4)
With Automatic Reference Counting, you're not supposed to retain and release objects yourself anymore.Williwaw
I know, but this answer was written in 2011.Berkey
The method is depreciated since IOS 9.0. Use instead UIAlertController:Russian
If you're looking support with Swift 4: https://mcmap.net/q/172441/-what-39-s-a-simple-way-to-get-a-text-input-popup-dialog-box-on-an-iphoneDiner
D
192

To make sure you get the call backs after the user enters text, set the delegate inside the configuration handler. textField.delegate = self

Swift 3 & 4 (iOS 10 - 11):

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
    textField.placeholder = "Enter text:"
    textField.isSecureTextEntry = true // for password input
})
self.present(alert, animated: true, completion: nil)

In Swift (iOS 8-10):

enter image description here

override func viewDidAppear(animated: Bool) {
    var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Enter text:"
        textField.secureTextEntry = true
        })
    self.presentViewController(alert, animated: true, completion: nil)
}

In Objective-C (iOS 8):

- (void) viewDidLoad 
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Click" style:UIAlertActionStyleDefault handler:nil]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Enter text:";
        textField.secureTextEntry = YES;
    }];
    [self presentViewController:alert animated:YES completion:nil];
}

FOR iOS 5-7:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"INPUT BELOW" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];

enter image description here


NOTE: Below doesn't work with iOS 7 (iOS 4 - 6 Works)

Just to add another version.

UIAlert With UITextField

- (void)viewDidLoad{

    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Preset Saving..." message:@"Describe the Preset\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
    UITextField *textField = [[UITextField alloc] init];
    [textField setBackgroundColor:[UIColor whiteColor]];
    textField.delegate = self;
    textField.borderStyle = UITextBorderStyleLine;
    textField.frame = CGRectMake(15, 75, 255, 30);
    textField.placeholder = @"Preset Name";
    textField.keyboardAppearance = UIKeyboardAppearanceAlert;
    [textField becomeFirstResponder];
    [alert addSubview:textField];

}

then I call [alert show]; when I want it.

The method that goes along

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {         
    NSString* detailString = textField.text;
    NSLog(@"String is: %@", detailString); //Put it on the debugger
    if ([textField.text length] <= 0 || buttonIndex == 0){ 
        return; //If cancel or 0 length string the string doesn't matter
    }
    if (buttonIndex == 1) {
        ...

    }
}

Diner answered 21/5, 2012 at 16:52 Comment(10)
I had something like this since IOS 4 but it seems to break in OS 7 Now use Wakrst's code - save many lines of code.Rostov
So, what would be the correct way of doing this for iOS7? We are building with iOS6 SDK but it still shows weird on iOS7.Infinite
Added iOS7 support to the questionDiner
This is not really "For iOS7", this new way of presenting a popup ith an text input is available since iOS 5.Mesothorax
You are correct, it's not exactly for iOS7 but the recommended way of doing it. I added "FOR iOS 5-7" to the post...Diner
Found I had to put the following in my alertView:(UIAlertView *) clickedButtonAtIndex:(NSInteger)buttonIndex delegate method in order to fetch the value of the textField.text: ` NSString *theMessage = [alertView textFieldAtIndex:0].text;`Gilbertson
UIAlertController show small strings. when the size of string become larger. then some text from this alert is missing. please help me how to solve this problem. is there any scrolling functionality avaliable so that to scroll to the remaining text.?Merrymerryandrew
I would post a new question as thats a specific discussion that the comments are not meant for. @IbadUrRahmanDiner
replace "var alert" with "let alert" in the swift code to comply with the latest version of swiftGuideboard
Very detailed, thank you. You could also point out the fact that we can process the info in UITextField once a action button is tapped by putting something like let myTextField = alert.textFields![0] as UITextField in the action's handler. This should be the right answer anyway though.Silhouette
R
13

Since IOS 9.0 use UIAlertController:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
                                                           message:@"This is an alert."
                                                          preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction * action) {
                    //use alert.textFields[0].text
                                                       }];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {
                                                          //cancel action
                                                      }];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    // A block for configuring the text field prior to displaying the alert
}];
[alert addAction:defaultAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
Russian answered 25/1, 2016 at 19:39 Comment(0)
J
12

Tested out Warkst's third code snippet--worked great, except I changed it to be default input type instead of numeric:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Please enter your name:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeDefault;
alertTextField.placeholder = @"Enter your name";
[alert show];
Junejuneau answered 29/12, 2011 at 2:32 Comment(1)
Good point! I was messing about with the textField at the time and forgot to change the keyboard type before uploading the code snippet. Glad my code could help you!Berkey
S
7

Try this Swift code in a UIViewController -

func doAlertControllerDemo() {

    var inputTextField: UITextField?;

    let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert);

    passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.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.doAlertViewDemo(); //do again!
    }));


    passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        print("done");
    }));


    passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Password"
        textField.secureTextEntry = false       /* true here for pswd entry */
        inputTextField = textField
    });


    self.presentViewController(passwordPrompt, animated: true, completion: nil);


    return;
}
Steeplejack answered 2/2, 2016 at 15:47 Comment(1)
The variable inputTextField is unnecessary, and I think causing problems for me. Get the text with passwordPrompt.textFields?.first?.text in the OK action. Also, you can remove the semi-colons.Alemanni
D
5

Just wanted to add an important piece of information that I believe was left out perhaps with the assumption that the ones seeking answers might already know. This problem happens a lot and I too found myself stuck when I tried to implement the viewAlert method for the buttons of the UIAlertView message. To do this you need to 1st add the delegate class which may look something like this:

@interface YourViewController : UIViewController <UIAlertViewDelegate>

Also you can find a very helpful tutorial here!

Hope this helps.

Disraeli answered 21/5, 2013 at 5:2 Comment(0)
S
3

Swift 3:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
     textField.placeholder = "Enter text:"
})

self.present(alert, animated: true, completion: nil)
Sulfur answered 15/12, 2016 at 9:21 Comment(0)
F
3

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;
}
Faugh answered 27/7, 2021 at 0:27 Comment(0)
N
2

I would use a UIAlertView with a UITextField subview. You can either add the text field manually or, in iOS 5, use one of the new methods.

Nalda answered 12/6, 2011 at 0:47 Comment(3)
I added the following code from another post, but the popup shows up off the screen (very much on top, with only the bottom half visible)Gnawing
code UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Your title here" message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)]; CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 130.0); [myAlertView setTransform:myTransform]; [myTextField setBackgroundColor:[UIColor whiteColor]]; [myAlertView addSubview:myTextField]; [myAlertView show]; [myAlertView release];Gnawing
I tried similar code and it displays the alert view with text box and buttons but there is not enough room for the textfield, it is stuck between the title and the buttons and touches them both. I tried some transforms to scale the frame but the buttons stay where they were so then they need to be moved also. I don't know how to reposition the buttons and I can't believe that all this is necessary to retrieve a single line of text from a prompt to the user. Isn't there a better way than this?Primordial
P
2

Add views to a UIAlertView like this. In iOS 5 there are some "magic" things that do it for you (but that's all under NDA).

Peggiepeggir answered 12/6, 2011 at 0:57 Comment(2)
I tried this and it does somewhat work. Except the popup is off the screen (the top half of the popup is chopped off). Any ideas why?Gnawing
I had the same problem, removing the setTranformMakeTranslation(0,109) fixed it for me on both ipad and iphone. It showed up in the right place without it.Latin
E
2

In Xamarin and C#:

var alert = new UIAlertView ("Your title", "Your description", null, "Cancel", new [] {"OK"});
alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
alert.Clicked += (s, b) => {
    var title = alert.ButtonTitle(b.ButtonIndex);
    if (title == "OK") {
        var text = alert.GetTextField(0).Text;
        ...
    }
};

alert.Show();
Eboat answered 7/8, 2016 at 18:37 Comment(0)
E
0

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
        })
Eidetic answered 13/3, 2019 at 0:1 Comment(0)
E
-1
UIAlertview *alt = [[UIAlertView alloc]initWithTitle:@"\n\n\n" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(25,17, 100, 30)];
lbl1.text=@"User Name";

UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(25, 60, 80, 30)];
lbl2.text = @"Password";

UITextField *username=[[UITextField alloc]initWithFrame:CGRectMake(130, 17, 130, 30)];
UITextField *password=[[UITextField alloc]initWithFrame:CGRectMake(130, 60, 130, 30)];

lbl1.textColor = [UIColor whiteColor];
lbl2.textColor = [UIColor whiteColor];

[lbl1 setBackgroundColor:[UIColor clearColor]];
[lbl2 setBackgroundColor:[UIColor clearColor]];

username.borderStyle = UITextBorderStyleRoundedRect;
password.borderStyle = UITextBorderStyleRoundedRect;

[alt addSubview:lbl1];
[alt addSubview:lbl2];
[alt addSubview:username];
[alt addSubview:password];

[alt show];
Eraser answered 15/9, 2014 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.