UIAlert View with UITextField and Controls


Apples philosophy with UIAlert view is to deliver alerts and offer very limited control. There are many hacks on the internet to add a UITextField subview and use its value. The most effective way I found to do this is as follows:

Alright, here's the goods. The first thing that you'll want to do is to alloc your UIAlertView and then initWithTitle:message:delegate:cancelButtonTitle: otherButtonTitles: just like normal. Then with all that good stuff done, you use the method addTextFieldWithValue:label:. The value is for initializing some text into the text field. The label is for setting a placeholder. Here's some example code.

Code:
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Alert title" message:@"alert message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil]; [myAlert addTextFieldWithValue:nil label:@""]; [[myAlert textField] setTextAlignment:UITextAlignmentCenter]; [[myAlert textField] becomeFirstResponder]; [myAlert show]; [myAlert release]; myAlert = nil;
If you don't tell the text field to become first responder before showing the alert view, you'll wind up with two keyboards. That took a little messing with to get things straightened out. Then, to access the value that was entered into the text field when the ok button is clicked, you just do something like this. In this particular example, myString is an iVar that's already been alloc'ed and init'ed. Thus far, I've not figured out a way to make the text field return if the user presses the return button on the keyboard. I've tried all kinds of things and nothing that I've tried works.

Code:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {      switch(buttonIndex) {          case 0:               [myString setText:@"Cancel button pressed"];               break;          case 1:               [myString setText:[[alertView textField] text]];               break;      } }
Just so you know, this will compile and you will get some warnings saying that UIAlertView may not respond to the messages, but it will.

It is undocumented but works flawlessly.

Comments

  1. Have you had an app approved with this functionality? I'm asking because Apple is often loathe to approve apps that use undocumented API features.

    thanks, Chuck

    ReplyDelete

Post a Comment