UIAlertView with UITextField

No comments on UIAlertView with UITextField

Written by

in

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:

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

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

<br />
– (BOOL)textFieldShouldReturn:(UITextField *)textField<br />
{<br />
    [textField resignFirstResponder];<br />
    return YES;<br />
}</p>
<p>– (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex<br />
{<br />
    NSLog(@”Button index clicked:%d”, buttonIndex);</p>
<p>    switch (buttonIndex) {<br />
        case 0:<br />
            break;<br />
        case 1:{<br />
            NSLog(@”Save Clicked”);<br />
            UITextField *textField = [alertView textFieldAtIndex:0];<br />
            NSString *text = textField.text;</p>
<p>            break;<br />
        }<br />
        default:<br />
            break;<br />
    }<br />
}<br />

References:
StackOverFlow question

Comments

Leave a Reply

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