UIAlertView - 从通过代码添加的文本字段中检索文本字段值

时间:2010-03-13 21:13:32

标签: iphone xcode

以下是我用文本框创建UIAlertView的代码。

    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];  

我的问题是,如何从文本字段中获取值:

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

}

我知道我可以获得alertview的标准内容,例如actionSheet.tag等,但是我如何获得上面创建的文本字段?

2 个答案:

答案 0 :(得分:6)

@interface MyClass {
    UITextField *alertTextField;
}

@end

而不是在本地声明它,只需使用它。

    //...
    alertTextField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)];
    //...

- (void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *text = alertTextField.text;
    alertTextField = nil;
}

答案 1 :(得分:6)

只需给它一个标签,稍后再使用标签找到它。所以,使用你的代码:

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];

然后,在回调中,无论发生在哪里,都不必担心文本字段的内存管理或状态管理:

- (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]);
}