方法一
首先在Interface Builder中选择TextFields,然后在Text Field Attributes中找到Text Input Traits,选择Return Key为done。OK
定义方法
- (IBAction) textFieldDoneEditing:(id)sender; //按下Done键关闭键盘
然后找到事件Did End On Exit,与textFieldDoneEditing关联,OK。
实现方法
//按完Done键以后关闭键盘
- (IBAction) textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
方法二
代码是在一个viewController里面,if语句中的判断self.view指的就是背景。touchesBegan:withEvent:是声明在UIResponder中的一个函数,当一个或多个手指在view或者window上触摸时会调用该函数。默认没有做任何事情。这里重写它。
// 触摸背景,关闭键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
UIView *view = (UIView *)[touch view];
if (view == self.view) {
[<textField> resignFirstResponder];
}
}
总结:
01 让文本框成为第一响应者(叫出键盘)
[ <textField> becomeFirstResponder];
02 让文本框退出第一响应者(退出键盘)
[ <textField> resignFirstResponder];
03 结束输入
[<textField>endEditing:YES];