Tuesday, August 2, 2011

How to add UITextField to UIAlertView from XIB

Today, I am going to share how to add UITextFields to UIAlertView from XIB. 
UITextFields can be added through coding, but I prefer draw it in a small view from XIB because it is more convenient and visualizable. In the following example, I will add 3 UITextFields and 4 UILabels in the small view.

1. Create a view_controller and add the customized small view(named AlertXIB in the picture, while named "changePasswordView" in the code) parallel to the main view of the view_controller. Add certain number of UILabels and/or UITextfields in the small view. As shown in the picture:

2. Add the view into the view_controller' main view on a button click.

-(IBAction)buttonClicked:(UIButton*) button {
//If I don't add this _fakeTextField, my own textfields won't be able to detect inputs from keyboard, another good thing is that the alertview will be automatically moved up a bit.
UITextField * _fakeTextField=[[UITextField alloc] initWithFrame:CGRectMake(12, 3, 200, 30)];
_fakeTextField.backgroundColor=[UIColor clearColor];

UIAlertView *_myAlertView = [[UIAlertView alloc] initWithTitle:nil message:@"\n\n\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
changePasswordView.frame=CGRectMake(12, 3, changePasswordView.frame.size.width, changePasswordView.frame.size.height);
[_myAlertView addSubview:_fakeTextField];
[_fakeTextField release];
[_myAlertView addSubview:changePasswordView];
[_myAlertView show];
[_myAlertView release];

A few things to explain here:
1). The message of the UIAlertView, I use several newline characters, because the message will be determine the size of the UIAlertView.

2). A "_fakeTextField" is also added, reason is what i explained in the comment. You can play around with it. For all the UITextfields "newPassword, oldPassword, confirmPassword", you can configure their UITextFieldDelegate via XIB or code. 

3). delegate of the UIAlertView is set to self (the view_controller), so you can handle further processing when user clicks button on the UIAlertView.

#pragma mark -
#pragma mark UIAlertViewDelegate

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
NSLog(@"button at index 0, cancel and doing nothing");
} else {
//Change password code here
NSLog(@"button at index 1");

3. So when the button click method (buttonClicked:) is called, the view will look like this. The UILabel text in the UIAlertView is in black color is just for demo, while you can change it to any color or size you want.