标签:class code tar ext color http
UITextField展示的是一些可编辑的内容,并且与用户有一些交互。比如当你在虚拟键盘上按下return键时,一般会关联到键盘隐藏事件上。UITextField的一些状态大多在UITextFieldDelegate协议中有相应的方法。
```objc
//姓名输入域
UITextField *nameField = [[UITextField alloc] initWithFrame:CGRectMake(30, 30, 200, 44)];
nameField.tag = 100;
nameField.delegate = self;
//默认文字
nameField.placeholder = @"name";
nameField.font = [UIFont systemFontOfSize:16.0f];
nameField.textColor = [UIColor blackColor];
//输入框的背景图片(还可以选择设置背景颜色)
nameField.background = [UIImage imageNamed:@"textFieldBackgroundImage"];
//nameField.backgroundColor = [UIColor lightGrayColor];
//清除按钮
nameField.clearButtonMode = UITextFieldViewModeAlways;
//键盘类型
nameField.keyboardType = UIKeyboardTypeDefault;
[self.view addSubview:nameField];
电话输入域
UITextField *phoneField = [[UITextField alloc] initWithFrame:CGRectMake(30, nameField.frame.origin.y + nameField.bounds.size.height+10, 200, 44)];
phoneField.tag = 101;
phoneField.delegate = self;
phoneField.placeholder = @"phone";
phoneField.keyboardType = UIKeyboardTypeDecimalPad;
phoneField.clearButtonMode = UITextFieldViewModeAlways;
[self.view addSubview:phoneField];
//邮箱输入域
UITextField *emailField = [[UITextField alloc] initWithFrame:CGRectMake(30, phoneField.frame.origin.y + phoneField.bounds.size.height + 10, 200, 44)];
emailField.tag = 102;
emailField.delegate = self;
emailField.placeholder = @"email";
emailField.keyboardType = UIKeyboardTypeEmailAddress;
emailField.clearButtonMode = UITextFieldViewModeAlways;
[self.view addSubview:emailField];
```
1.点击键盘的return来隐藏键盘
这个方法需要在相应的.h文件文件中实现UITextFieldDelegate协议。并在.m文件中添加如下方法
```objc
```
2.点击界面空白处来隐藏键盘
这个方法的实现主要是给当前的view增加点击事件,并未点击事件增加相应的处理方法,此处是为了隐藏键盘,所以我们可以在点击事件对应的方法中让UITextField放弃第一响应者。
```objc
```
为当前的view增加点击事件
```objc
UITapGestureRecognizer *dismissKeyboardTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]; [self.view addGestureRecognizer: dismissKeyboardTap];
```
```objc
```
iOS开发之UITextField,布布扣,bubuko.com
标签:class code tar ext color http
原文地址:http://www.cnblogs.com/dreamfree/p/3709627.html