UIAlertView - get the value of a text field from a text field added by code

Here is the code I have to create a UIAlertView with a text box.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter A Username Here" message:@"this gets covered!" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:@"OK!", nil]; UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)]; CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60); [alert setTransform:myTransform]; alert.tag = kAlertSaveScore; [myTextField setBackgroundColor:[UIColor whiteColor]]; [alert addSubview:myTextField]; [alert show]; [alert release]; [myTextField release]; 

My question is: how do I get a value from a text box in:

 - (void) alertView:(UIAlertView *) actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { } 

I know that I can get standard material for alertview, such as actionSheet.tag, etc., but how would I get the text box received above?

+4
source share
2 answers
 @interface MyClass { UITextField *alertTextField; } @end 

And instead of declaring it locally, just use this.

  //... alertTextField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)]; //... - (void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSString *text = alertTextField.text; alertTextField = nil; } 
+6
source

Just give it a tag and find it with the tag later. So using your code:

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter A Username Here" message:@"this gets covered!" delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:@"OK!", nil]; UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)]; CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60); [alert setTransform:myTransform]; alert.tag = kAlertSaveScore; // Give the text field some unique tag [myTextField setTag:10250]; [myTextField setBackgroundColor:[UIColor whiteColor]]; [alert addSubview:myTextField]; [alert show]; [alert release]; [myTextField release]; 

Then in the callback, wherever it is, and without worrying about managing memory or managing the state of the text field:

 - (void) alertView:(UIAlertView *) actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { // Get the field you added to the alert view earlier (you should also // probably validate that this field is there and that it is a UITextField but...) UITextField* myField = (UITextField*)[actionSheet viewWithTag:10250]; NSLog(@"Entered text: %@", [myField text]); } 
+6
source

Source: https://habr.com/ru/post/1304035/


All Articles