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
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]); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With