0

大家好,我无法从 AlertView TextField 获取值/文本。也许有人可以看看我的代码,看看我做错了什么。每次我按 OK 时,标签都会得到一个(空)值。我一定在这里遗漏了一些东西。

TextFieldINAlertViewController.h

#import <UIKit/UIKit.h>

@interface TextFieldInAlertViewController : UIViewController {

UITextField *myTextField;
IBOutlet UILabel *labelView;
NSString *FieldStr1;

}


@property (nonatomic, copy) NSString *FieldStr1;




@end  

TextFieldInAlertViewController.m

#import "TextFieldInAlertViewController.h"

@implementation TextFieldInAlertViewController


@synthesize FieldStr1;


- (void)viewDidLoad {
[super viewDidLoad];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter Name Here" message:@"blank" 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];
[myTextField setBackgroundColor:[UIColor whiteColor]];
[alert addSubview:myTextField];
[alert show];
[alert release];

}

-(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)index
{
if (index == 0){
    return;
}
if (index == 1){


    FieldStr1 = myTextField.text;
    labelView.text = [NSString stringWithFormat:@"%@" , FieldStr1 ];
}
}



- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

}

- (void)viewDidUnload {

}


- (void)dealloc {
[super dealloc];
}

@end
4

2 回答 2

0

myTextField 是 viewDidLoad 中的局部变量,但它也是您类中的成员变量。摆脱本地声明,你应该没问题。另外,我会将此代码移至 viewDidAppear:,而不是 viewDidLoad。

于 2009-12-30T22:05:25.527 回答
0

从 iOS5 开始,您可以在 alertView 上使用属性,这是一种更简单的添加文本字段的方法。

如果你想给 UIAlertView 添加一个 TextField,你可以为 UIAlertView 使用这个属性(alertViewStyle):

- (void)showAlert{
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message"             delegate:self cancelButtonTitle:@"Done" otherButtonTitles:nil];
  alert.alertViewStyle = UIAlertViewStylePlainTextInput;
  ((UITextField *) [alertView textFieldAtIndex:0]).text = @"Default Value";
  [alert show];

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  NSLog(@"%@", [alertView textFieldAtIndex:0].text);
}

检查 UIAlertView 参考:http: //developer.apple.com/library/ios/#documentation/uikit/reference/UIAlertView_Class/UIAlertView/UIAlertView.html

雨果

于 2013-03-17T21:31:48.803 回答