在ViewController.h里面声明对象和属性,并加上代理UITextFieldDelegate:
#import
@interface ViewController : UIViewController {
//定义一个textField //文本输入区域 //例如:用户名,密码等需要输入文本文字的内容区域 //只能输入单行的文字,不能输入或者显示多行 UITextField * _textField;
}
//定义属性@property(retain,nonatomic) UITextField * textField;
@end
在 ViewController.m进行实现:
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController@synthesize textField =_textField;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. //创建一个文本输入区对象,UITextField是继承UIControl,UIControl是继承UIView self.textField = [[UITextField alloc]init];
//设定文本输入区位置 self.textField.frame = CGRectMake(100, 100, 180, 40);
//设置textField的内容文字 self.textField.text=@"";
//设置字体的大小 self.textField.font=[UIFont systemFontOfSize:15];
//设置字体的颜色 self.textField.textColor=[UIColor blackColor];
//设置边框的风格 //UITextBorderStyleRoundedRect:圆角风格,默认就是圆角风格 //UITextBorderStyleLine:线框风格 // UITextBorderStyleBezel:bezel线框 // UITextBorderStyleNone:无边框风格 self.textField.borderStyle = UITextBorderStyleRoundedRect;
//设置虚拟键盘风格 //UIKeyboardTypeNumberPad:纯数字风格 //UIKeyboardTypeNamePhonePad:字母和数字组合风格 //UIKeyboardTypeDefault:默认风格// self.textField.keyboardType =UIKeyboardTypeDefault;
self.textField.keyboardType =UIKeyboardTypeNumberPad;
//提示文字信息 //当text属性为空,显示此条信息 //浅灰色提示文字 self.textField.placeholder=@"请输入用户名";
//是否作为密码输入 //YES:作为处理,圆点加密 //NO:正常显示输入的文字 self.textField.secureTextEntry=YES;
[self.view addSubview:self.textField];
//设置代理对象 self.textField.delegate=self;
}
-(void) textFieldDidBeginEditing:(UITextField *)textField{
NSLog(@"开始编辑了");
}
-(void) textFieldDidEndEditing:(UITextField *)textField{
NSLog(@"编辑输入结束");
self.textField.text=@"";
}
//是否可以进行输入//如果返回值为YES,可以进行输入,默认为YES;
//NO:不能输入文字,键盘弹不出来-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField{
return YES;
}
//是否可以结束输入//如果返回值为YES:可以结束输入,默认为YES;
//NO:不能结束输入文字,键盘不能收回-(BOOL) textFieldShouldEndEditing:(UITextField *)textField{
return YES;
}
//点击屏幕空白处调用此函数-(void) touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
//使虚拟键盘回收,不再作为第一消息响应者 [self.textField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.}
@end