UIAlertView with UITextField

I wanted to show an alertView to a user with a textField. This is what was achieved:

First, I tried to use Block Alerts and ActionSheets, but I failed. Then I discovered, that there is a standart way to do this. There are some UIAlertView styles available beyond a default style: UIAlertViewStyleLoginAndPasswordInput, UIAlertViewStylePlainTextInput and UIAlertViewStyleSecureTextInput. In this case we will use the second one. Works on iOS 5 and later:

UIAlertView *av = [[UIAlertView alloc] initWithTitle:LS(@"Document file name") message:@"Please enter document file name." delegate:self cancelButtonTitle:LS(@"Cancel") otherButtonTitles:LS(@"Save"), nil];
av.alertViewStyle = UIAlertViewStylePlainTextInput;
[av textFieldAtIndex:0].delegate = self;
[av textFieldAtIndex:0].text = self.mcAttachDisplayed.fileName;
[av show];

Then, you should define two protocols UITextFieldDelegate, UIAlertViewDelegate.
And implement methods:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
    [textField resignFirstResponder];
    return YES;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    NSLog(@"Button index clicked:%d", buttonIndex);
    switch (buttonIndex) {
        case 0:
        case 1:{
            NSLog(@"Save Clicked");
            UITextField *textField = [alertView textFieldAtIndex:0];
            NSString *text = textField.text;

StackOverFlow question

Leave a Reply

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