iOS: Text input on popup dialog box


Before iOS 5 there was not an easy way to create a text input box inside a popup dialog box (UIAlertView). So on a project I was working on, I figured out a way to create one. This works with iOS 4 and up. I also have provided iOS 5's new way of doing it without my little hack. If you are interested in supporting iOS 4, then my code is very useful, but if not, then I suggest sticking with iOS 5 version. If you have any questions ask.

iOS 4
[code]
- (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;
textField = [[UITextField alloc] init];
[textField setBackgroundColor:[UIColor whiteColor]];
textField.delegate = self;
textField.borderStyle = UITextBorderStyleLine;
textField.frame = CGRectMake(15, 75, 255, 30);
textField.font = [UIFont fontWithName:@"ArialMT" size:20];
textField.placeholder = @"Preset Name";
textField.textAlignment = UITextAlignmentCenter;
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
[textField becomeFirstResponder];
[alert addSubview:textField];
}
[/code]

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

The method that goes along

[code]
- (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) {
//code here for when ok is pressed

}
}[/code]

In addition, it's useful to use the latest way to create one.

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

Related Posts