Unable to add UITextField to UIAlertView on iOS7...works in iOS 6

iTrout picture iTrout · Aug 31, 2013 · Viewed 36.6k times · Source

The code below works on iOS6 (and before) but the UITextField does not display in iOS7...any ideas on how to get a UITextField to display in an UIAlterView in iOS7?

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];
[dialog release];

[nameField release];

Code run for iOS6 displays this:

enter image description here

same code in iOS7 displays this (notice how UITextField is missing and there is no keyboard):

enter image description here

Answer

Aaron Brager picture Aaron Brager · Aug 31, 2013

You can't easily alter the view hierarchy of a UIAlertView in iOS 7. (Nor should you; the documentation specifically tells you not to.) Head over to the developer forums to see a long discussion about it.

One alternative in your case is to set alert.alertViewStyle = UIAlertViewStylePlainTextInput; This will add a text field for you. You can access it in the UIAlertView delegate callback by using UITextField *textField = [alertView textFieldAtIndex:0];.