Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I init a text field in a UIAlertView

The updated UIAlertView now has a style which allows a Text input field in UIAlertView i.e.

alert.alertViewStyle = UIAlertViewStylePlainTextInput;

This works well but I wanted to init the input text with a defualt text like "sample".

I see that folks in the past have used undocumented api like (which works great)

[alert addTextFieldWithValue:@"sample text" label:@"Text Field"];

but since this is still not an official Apple public API I can't use it.

Any other way to handle this? I did try to init in willPresentAlertView but text field seem to be read-only.

Thanks

like image 284
timeview Avatar asked Mar 08 '12 14:03

timeview


4 Answers

The UIALertView has a textFieldAtIndex: method that returns the UITextField object you want.

For a UIAlertViewStylePlainTextInput, the index of the textfield is 0.

You can then set the placeholder (or text) property of the textfield:

UIAlertView *alert = .... UITextField *textField = [alert textFieldAtIndex:0]; textField.placeholder = @"your text"; 

UIAlertView Class Reference

like image 196
Mutix Avatar answered Oct 09 '22 07:10

Mutix


Easy way to do

 UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"your title" message:@"your message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    alerView.alertViewStyle = UIAlertViewStylePlainTextInput;
    [[alerView textFieldAtIndex:0] setPlaceholder:@"placeholder text..."];
    [alerView show];
like image 31
Dipu Rajak Avatar answered Oct 09 '22 05:10

Dipu Rajak


Not tested, but I assume this would work:

UIAlertView* alert = [[UIAlertView alloc] initWithTitle:...];
UITextField* textField = [alert textFieldAtIndex:0];
textField.text = @"sample";
[alert show];
like image 31
Stephen Darlington Avatar answered Oct 09 '22 06:10

Stephen Darlington


For setting default value in uiAlertView this thing will work.

UIAlertView *alert = ....
UITextField *textField = [alert textFieldAtIndex:0];
[textField setText:@"My default text"];
[alert show];
like image 23
Salman Iftikhar Avatar answered Oct 09 '22 05:10

Salman Iftikhar