一、 在iOS程序中当想要在文本框中输入数据,轻触文本框会打开键盘。对于 iPad程序,其键盘有一个按钮可以用来关闭键盘,但是 iPhone程序中的键盘却没有这样的按钮,不过我们可以采取一些方法关闭它。例如,我们可以实现按下 Rerun(有时也是 Done、Research等)键关闭键盘,或者,更人性化的,轻触背景关闭键盘。
1、直接用控件实现按下Return键关闭键盘。
当按下键盘的 Return键,会产生一个 Did End On Exit事件,此时,我们告诉文本框要放弃控件,于是键盘就消失了。
假设,我们已经创建了一个 SingleView Application,并打开 ViewController.xib文件,在 View上拖上去了1个 Text Field ,然后,我们把这个文本框映射到 ViewController.h中,名称依次是 firstField。
在这个基础上,实现轻触 Return关闭键盘,步骤为:
(1)在ViewController.h中声明一个方法
- (IBAction)textFiledReturnEditing:(id)sender;
(2)在 ViewController.m中实现这个方法:
-(IBAction)textFiledReturnEditing:(id)sender {
[sender resignFirstResponder];
}
所谓 First Responder指的就是用户当前正在与之交互的控件。当用户使用键盘时,First Responder就是这个键盘,resignFirstResponder方法,顾名思义,就是放弃 First Responder。
(3)让这文本框映射到 textFiledReturnEditing方法,不过此时的事件应当是 DidEnd On Exit,具体操作是:
打开 Assistant Editor ,左边打开 ViewController.xib,右边打开 ViewController.h,在 Xcode最右边打开 Connector Inspector,然后在 View中选择文本框,在 Connector Inspector中找到 Did End On Exit,从它右边的圆圈中拉出映射线,映射到ViewController.h的 textFiledReturnEditing方法,
2、也可以用代码生成文本框并生成与之关联的方法
在ViewController.h的viewDidLoad方法中添加如下代码:
[self addTextField:nil];
然后添加如下方法:
- (void)addTextField:(id)sender
{
UITextField *pTextField=[UITextField alloc]initWithFrame:CGRectMake(10,10,300,20)];
pTextField。backgroundColor=[UIColor greenColor];
[self.view addSubview:pTextField];
[self.view addTarget:sender action:@selector(fieldActin:) forControlEvents:UIControlEventEditingDidOnExit];
[pTextField release];
}
- (void)fieldAction:(id)sender
{
[sender resignFirstResponder];
}
3、轻触背景关闭按钮
方法1》首先定义一个方法,然后实现这个方法,接下来将指定的控件映射到这个方法,并选择好所触发的事件。不同的是,这次我们要选择的控件不是上边的文本框,而是视图 View本身。
(1)在 ViewController.h文件中添加方法声明代码:
- (IBAction)backgroundTap:(id)sender;
(2)在ViewController.m中实现这个方法:
- (IBAction)backgroundTap:(id)sender
{
[pTextField resignFirstResponder];
}
需要说明的是,[pTextField resignFirstResponder];表示,如果pTextField有FirstResponder的话就放弃它,我们不用先判断pTextField是否有,这条语句完全正确。
(3)让 View映射到这个方法,不过事先,我们先要改变 View的类型。
打开xib,选中 View,打开 Identity Inspector,在 class中选择 UIControl
(4)打开Assistant Editor,左边打开 ViewController.xib,右边打开 ViewController.h,在Xcode最右边打开 Connector Inspector,在 ViewController.xib中选择Control,在 Connector Inspector 中找到 Touch Down,从它右边的圆圈中拉出映射线,映射到ViewController.h的 backgroundTap方法,如下图:
方法2》直接在touchesBegan方法中让视图结束编辑状态
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.viewendEditing:YES];
}
二、文本框键盘样式:
1、英文键盘:
- UIKeyboardTypeAlphabet(Alphabet字母)
- UIKeyboardTypeASCIICapable
- UIKeyboardTypeDefault
2、数字键盘
- UIKeyboardTypeDecimalPad (Decimal十进制)
- UIKeyboardTypeEmailAddress
4、没有符号的英文键盘
- UIKeyboardTypeNamePhonePad
5、没有小数点的数字键盘
- UIKeyboardTypeNumberPad
- UIKeyboardTypeNumbersAndPunctuation
- UIKeyboardTypePhonePad
- UIKeyboardTypeTwitter