AlertView与TextField问题

时间:2009-12-30 20:22:11

标签: iphone objective-c iphone-sdk-3.0 textfield

嘿伙计们,我无法从AlertView TextField获取值/文本。也许有人可以查看我的代码,看看我做错了什么。每按一次OK,标签就会得到一个(null)值。我必须在这里遗漏一些东西。

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

如果要将TextField添加到UIAlertView,可以将此属性(alertViewStyle)用于UIAlertView:

- (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

格·