Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField in UIAlertView on iPhone - how to make it responsive?

Tags:

I placed a UITextField into a UIAlertView and moved it up so the keyboard wouldn't cover it up with the following code:

[dialog setDelegate:self]; [dialog setTitle:@"Enter Name"]; [dialog addButtonWithTitle:@"Cancel"]; [dialog addButtonWithTitle:@"OK"]; UITextField * nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)]; [nameField setBackgroundColor:[UIColor whiteColor]]; [dialog addSubview:nameField]; CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 100.0); [dialog setTransform: moveUp]; [dialog show]; 

I also have the following code to deal with the alert view:

- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{         NSLog(@"%d", (int) buttonIndex);     if (buttonIndex == 1) { // OK pushed         NSLog([alert textField].text); // does not log anything     } else {         // Cancel pushed }} 

I also have a UIAlertViewExtended.h file that contains:

@class UITextField, UILabel;  @interface UIAlertView(Extended)  -(UITextField *)textField;  @end 

My question is how do I get the text the user entered and how do I dismiss the keyboard?

Thanks, Ben

like image 228
user21293 Avatar asked Dec 17 '08 21:12

user21293


1 Answers

Anyone supporting iOS 5.0 onwards with ARC, there's this direct alertViewStyle property you can set:

-(void)showAlertWithTextField{     UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:@"Enter Name" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add", nil];         [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];      // Change keyboard type     [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];     [dialog show]; }  -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{     if (buttonIndex == 1)         NSLog(@"%@",[[alertView textFieldAtIndex:0]text]); } 
like image 108
chunkyguy Avatar answered Jan 01 '23 21:01

chunkyguy