繁体   English   中英

AlertView与TextField问题

[英]AlertView with TextField Problem

大家好,我无法从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

从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

胡格斯

myTextField是viewDidLoad中的局部变量,但它也是类中的成员变量。 摆脱本地声明,就可以了。 另外,我将这段代码移到viewDidAppear:而不是viewDidLoad。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM