Md Nasir Uddin
Md Nasir Uddin

Reputation: 2190

How can I get a value from UITextField in UIAlertView?

I have Used in cocos2d game engine. this is my code:

-(void)timed1: (id)sender {
    UIAlertView *dialog = [[[UIAlertView alloc] init] retain];
    [dialog setDelegate:self];
    [dialog setTitle:@"Enter Time:"];
    [dialog setMessage:@" "];
    UITextField *nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
    [dialog addSubview:nameField];
    [nameField setBackgroundColor:[UIColor whiteColor]];
    CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 70.0);
    [dialog setTransform: moveUp];
    [dialog addButtonWithTitle:@"Done"];
    [dialog addButtonWithTitle:@"Cancel"];

    nameField.clearButtonMode = UITextFieldViewModeWhileEditing;
    nameField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;

        //timeStatus is a int type global variable //   
     timeStatus =[nameField.text intValue];  //** this line not working**//  

    [nameField release];
    [dialog show];

}

Upvotes: 2

Views: 3880

Answers (2)

Andrew Grant
Andrew Grant

Reputation: 58804

The reason you cannot get a value is that the function will exit BEFORE the user types anything! When you call [dialog show] the dialog is displayed to the user where they may then enter text.

You should wait until the user selects a button, which will trigger your delegate function, and THEN access the text field property.

Note to do this you will either need to retain a pointer to the UITextField object you added (easiest), or find it again amongst the subviews and cast it.

Upvotes: 2

Sophie Alpert
Sophie Alpert

Reputation: 143204

Release nameField later, and get the text property from there.

Upvotes: 0

Related Questions