1、点击键盘return键,触发代码隐藏:
(1)当前UIController实现UITextFieldDelegate:
@interface KingViewController :UIViewController <UITextFieldDelegate> {
...
}
(2) 添加textField,在XB中连接其delegate为KingViewController
(3) 在KingViewController.m中实现:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField { // 这个方法是UITextFieldDelegate协议里面的
NSLog(@"textFieldShouldReturn the keyboard *** %@ ",theTextField.text);
if (theTextField == self.textField) {
[theTextField resignFirstResponder]; //这句代码可以隐藏 键盘
}
returnYES;
}
2、当UITextField设置键盘为Number时,没有return键,无法使用上面的方法,就试试下面的方法:
(1) 在xb中,选中背景的UIView,将其Custom Class由 UIView 修改为 UIControl
(2) 在KingViewController.h中声明一个IBAction:
(IBAction)clickBackground:(id)sender;
(3) 在xb中连接这个IBAction和Background的UIControl, Touch Up inside
(4) 在KingViewController.m中实现:
- (IBAction)clickBackground:(id)sender {
NSLog(@"clickBackground enter *** ");
int t = [self.mRootViewtag];
if(t ==1001) {
NSLog(@"you click background *** ");
[sender endEditing:YES]; //这句代码可以 隐藏键盘
//[[[UIApplication sharedApplication] keyWindow] endEditing:YES]; //一样的效果
}
}
3、跟2一样,可以实现点击空白处隐藏键盘:
(1)xib中拖一个UIButton,将大小拖到最大,覆盖到整个界面
(2)设置刚才的UIButton控件到最下面: Editor -> Arrangement ->send to Back
(3)同上面的2方法,设置UIButton的IBAction事件,并在IBAction事件中实现键盘隐藏:
在KingViewController.m中实现:
- (IBAction)clickBackground:(id)sender {
NSLog(@"clickBackground enter *** ");
int t = [self.mRootViewtag];
if(t ==1001) {
NSLog(@"you click background *** ");
[[[UIApplication sharedApplication] keyWindow] endEditing:YES]; //这句代码可以 隐藏键盘
}
}