FirstApp,iphone开发学习总结4,UITextField的值To UILabel

需要交互,在TextFieldViewController.h中创建2个变量,并实现UITextFieldDelegate(Return):

@interface TextFieldViewController : UIViewController<UITextFieldDelegate>{
    UILabel *resultLbl;
    UITextField *textField;
}
@property (retain, nonatomic) UILabel *resultLbl;
@property (retain, nonatomic) UITextField *textField;

在TextFieldViewController.m中:

@synthesize resultLbl;
@synthesize textField;

init:

- (id)init {
    self = [super init];
    if (self) {
        [self setTitle:@"文本展示"];
        
        UIImage *img = [UIImage imageNamed:@""];
        [[self tabBarItem] setImage:img];
    }
    return self;
}

在- (void)viewDidLoad中创建TextField、Button和一个Label:

- (void)viewDidLoad
{
    textField = [[UITextField alloc] init];
    textField.frame = CGRectMake(40.050.0240.030.0);
    textField.textAlignment = UITextAlignmentLeft;
    [textField setBorderStyle:UITextBorderStyleRoundedRect];
    textField.delegate = self;
    
    UIButton *btnOk = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnOk.frame = CGRectMake(180.0100.0100.030.0);
    [btnOk setTitle:@"OK" forState:UIControlStateNormal];
    [btnOk addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    
    resultLbl= [[UILabel alloc] init];
    resultLbl.frame = CGRectMake(110.0150.0100.050.0);
    resultLbl.text = @"0";
    resultLbl.textAlignment = UITextAlignmentCenter;
    resultLbl.font = [UIFont fontWithName:@"" size:10];
    
    [[self view] addSubview:btnOk];
    [[self view] addSubview:textField];
    [[self view] addSubview:resultLbl];
}

Button事件:

- (void)onClick:(id)sender
{
    if (textField.text) {
        [resultLbl setText:textField.text];
    }else{
        [resultLbl setText:@"NULL"];
    }
}

TextField失去焦点:

- (BOOL)textFieldShouldReturn:(UITextField *)text
{
    [textField resignFirstResponder];
    return 0;
}

释放:

- (void)dealloc
{
    [textField release];
    [resultLbl release];
    [super dealloc];
}

 

 有更好的方法,请指点,谢谢!

posted @ 2012-05-03 23:15  Maxfong  阅读(439)  评论(0编辑  收藏  举报