在iOS应用开发中,有三类视图对象会打开虚拟键盘,进行输入操作,但如何关闭虚拟键盘,却没有提供自动化的方法。这个需要我们自己去实现。这三类视图对象分别是UITextField,UITextView和UISearchBar。 这里介绍一下UITextField中关闭虚拟键盘的几种方法。
第一种方法,使用它的委托UITextFieldDelegate中的方法textFieldShouldReturn:来关闭虚拟键盘。
在UITextField视图对象如birdNameInput所在的类中实现这个方法。
(BOOL)textFieldShouldReturn:(UITextField *)textField {
if ((textField == self.birdNameInput) || (textField == self.locationInput)) {
[textField resignFirstResponder];
}
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if ((textField == self.birdNameInput) || (textField == self.locationInput)) {
[textField resignFirstResponder];
}
return YES;
}
这样,在输入框birdNameInput中打开虚拟键盘后,轻击键盘的return键就会自动关闭掉虚拟键盘。
第二种方法,将birdNameInput的属性中Return Key修改为done,再定义一个方法和Done键的Did End On Exit连接。
通过轻击done键触发这个事件来关闭虚拟键盘。
定义的方法如下:
(IBAction) textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
- (IBAction) textFieldDoneEditing:(id)sender
{
[sender resignFirstResponder];
}
这两个方法都是轻击虚拟键盘上一个键来关闭它。这属于精确操作,而手指不像鼠标,做这种操作不容易。因此就UI层面而言,这两个方法都不是最好的方法。 在iphone或ipad屏幕上,虚拟键盘占用的面积大小是有限的。通过轻击虚拟键盘之外的区域而关闭虚拟键盘。
第三种方法,通过轻击键盘之外的空白区域关闭虚拟键盘。










