读书人

用Button联接TextField和Label

发布时间: 2013-10-16 11:29:46 作者: rapoo

用Button连接TextField和Label

viewController.h文件:


#import <UIKit/UIKit.h>

#import <Foundation/Foundation.h>

@interface ViewController : UIViewController


{

//建立文本框

IBOutlet UITextField *textField;

//建立标签显示文字

IBOutlet UILabel *label;

}

@property(nonatomic, retain) UITextField *textField;

@property(nonatomic, retain) UILabel *label;

-(IBAction)Click:(id)sender;

@end


ViewController.m文件:

#import "ViewController.h"

@implementation ViewController

@synthesize textField, label;


- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

// 把已经读取的Label标签的文字替换成为本程序的显示内容

label.text = @"请输入文字";

}


-(IBAction)Click:(id)sender

{

int textCount = textField.text.length;

//当长度大于30

if (textCount > 30) {

//输出结果

label.text = @"Invalid Inputs";

//输入文字清空

textField.text = NULL;

}

// 如果长度不大于30

else {

//输出结果

NSString *result = [NSString stringWithFormat:@"输入长度为:%d", textCount];

label.text = result;

//清空文字

textField.text = NULL;

}

}

- (void)viewDidUnload

{

[super viewDidUnload];

// Release any retained subviews of the main view.

}


-(void) didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

}


//释放程序使用过的标签

-(void) dealloc

{

[label release];

[textField release];

//执行内存清理

[super dealloc];

}

@end


连接控件:

用Button联接TextField和Label


在textField属性中的placeholder可填入提示信息,效果如下:

用Button联接TextField和Label


连接控件:

用Button联接TextField和Label


运行程序:

用Button联接TextField和Label

总结:

这次学习的程序是运用textField.text.length输出长度,用NSString编写文字代码输入到Label控件中,使用Click方法对interface Builder内的Button控件和Label进行动态连接。点击Button控件对TextField内的文字数进行统计,Label控件显示计算结果。

读书人网 >移动开发

热点推荐