in iOS

IOS7 Bug: UIAlertView’s Designated Initializer “initWithTitle” and UITextField

When I used a UIAlertView window with a text field to capture text, the text would enter and pressing “Enter” dismissed the window, but no text was captured and no button events registered. I did however get a console full of dozens of various CGContext errors like this:

Oct 28 21:08:43 MacbookAir.local Nourish[29911] : CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.

Apparently the UIAlertView’s Designated Initializer initWithTitle is broken. I even had line-by-line the same code in two implementation files with two very different results. Instead you need to instantiate it step by step.

Instead of:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Enter some text" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Enter", nil];

Use:

UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:@"Title"];
[alert setMessage:@"Enter some text"];
[alert setDelegate:self];
[alert addButtonWithTitle:@"Cancel"];
[alert addButtonWithTitle:@"Enter"];

Then go ahead and add the rest:

[alert setAlertViewStyle = UIAlertViewStylePlainTextInput];
UITextField *input = [addressAlert textFieldAtIndex:0];
inputField = input;
[inputField setPlaceholder:@"Street address"];
[inputField setDelegate:self];
[addressAlert show];
[inputField becomeFirstResponder];

Voila. Bug averted.

Related Posts

Written By: