第一种方法:
谁叫出的键盘,那么谁就是“第一响应者”,让“第一响应者”辞职,就可以把键盘叫回去了
下面代码中依次把交出键盘的两个text文本框叫出的键盘给叫回去
[self.textNum2 resignFirstResponder];
[self.textNum1 resignFirstResponder];
大家会发现,这种方法很笨,因为一旦页面中有很多文本框的话或者其他控件需要叫出键盘的话,如果想在输入完文字
之后把键盘叫回去,那将会是一个很繁琐的的工程。因此,我们有了第二种方法,直接把界面中所有的键盘全部叫回去
第二种方法:
self.view就是当前控制器所管理的那个view(每一个控制器都会管理一个view)
这种方法把键盘叫回去的思路就是:让控制器所管理的view停止编辑,这样的话,凡是这个view中的子控件叫出的
键盘就都回去了
[self.view endEditing:YES];
第三种方法:
点击空白处直接叫回键盘
#pragma mark 点击空白处叫回键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self endEditing:YES];
}
其他控件上移:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//注册观察键盘的变化
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(transformView:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
//键盘回收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
for(UIView *view in self.view.subviews)
{
[view resignFirstResponder];
}
}
//移动UIView
-(void)transformView:(NSNotification *)aNSNotification
{
//获取键盘弹出前的Rect
NSValue *keyBoardBeginBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect beginRect=[keyBoardBeginBounds CGRectValue];
//获取键盘弹出后的Rect
NSValue *keyBoardEndBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect endRect=[keyBoardEndBounds CGRectValue];
//获取键盘位置变化前后纵坐标Y的变化值
CGFloat deltaY=endRect.origin.y-beginRect.origin.y;
NSLog(@"看看这个变化的Y值:%f",deltaY);
//在0.25s内完成self.view的Frame的变化,等于是给self.view添加一个向上移动deltaY的动画
[UIView animateWithDuration:0.25f animations:^{
[self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+deltaY, self.view.frame.size.width, self.view.frame.size.height)];
}];
}
@end