Tuesday, July 13, 2010

UIAlertView with a TextField within it

Every iphone developer would have seen default alert view with a title, a message and buttons to dismiss the alert view. Today I will show an option to insert an UITextField inside a UIAlerView.

We will basically call a UIAlertView and then add the UITextField programmatically.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Enter Your Name” message:@”message hidden by text field” delegate:self cancelButtonTitle:@”Dismiss” otherButtonTitles:@”OK!”, nil];
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)];
CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60);
[alert setTransform:myTransform];
[myTextField setBackgroundColor:[UIColor whiteColor]];
[alert addSubview:myTextField];
[alert show];
[alert release];
[myTextField release];

We are including a dummy message in the alert view because it's position will be occupied by our textfield. If we didn’t put that sentence then the alerts buttons would go up more and the UITextField will be messed up.

Next thing that we have used is CGAffineTransform. It is used because on focusing on the textfield, keyboard appears and covers some part of our UITextField. Hence this transform ensures that keyboard doesn't covers it up.

Now build and Run the application. You will get a screen as below.