How to add UITextField in UIAlertView in iOS 7

For iOS 6 and below we have been adding UITextField in UIAlertView by adding a subview in UIAlertView. Something like below –

UIAlertView* dialog = [[UIAlertView alloc] init];
[dialog setDelegate:self];
[dialog setTitle:@"Enter ESC Score"];
[dialog setMessage:@" "];
[dialog addButtonWithTitle:@"Cancel"];
[dialog addButtonWithTitle:@"OK"];
dialog.tag = 5;

nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
[nameField setKeyboardType:UIKeyboardTypeNumberPad];
[nameField becomeFirstResponder];
[nameField setBackgroundColor:[UIColor whiteColor]];
[dialog addSubview:nameField];
CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 0.0);
[dialog setTransform: moveUp];
[dialog show];

But in iOS 7 Apple have changed things in UIAlertView class and not its not possible to add things in UIAlertView. Also as per the documentation its not a good idea to do so.

Fortunately Apple already have a functionality by which we can add a UITextField in the UIAlertView.

There is a property “alertViewStyle” for UIAlertView. We can set this style to get desired UIAlertView.

See this example –

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Folder Name?" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil] ;
alertView.tag = 2;
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alertView show];

We can get this textfield in alert view’s delegate method like this –

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

            UITextField * alertTextField = [alertView textFieldAtIndex:0];
            NSLog(@"alerttextfiled - %@",alertTextField.text);

// do whatever you want to do with this UITextField.

Here are supported UIAlertView styles.

A standard alert.

An alert that allows the user to enter text. The text field is obscured.

An alert that allows the user to enter text.

An alert that allows the user to enter a login identifier and password.

Hope this would help and save someone’s some grey hair.

2 thoughts on “How to add UITextField in UIAlertView in iOS 7”

Leave a Reply

Your email address will not be published. Required fields are marked *