2010-03-13 66 views
4

這裏是我必須創建一個帶有文本框的UIAlertView的代碼。UIAlertView - 通過代碼添加文本框中的textfield值

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等,但如何我會得到上面創建的文本字段嗎?

回答

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