//注册通知
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//键盘出现
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//键盘回收
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
//移除通知
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
//键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
//获取处于焦点中的view
NSArray *textFields = @[_people_num, _scale,_leader_name,_leader_phoneNum]; //将需要上移的控件存在这个数组
UIView *focusView = nil;
for (UITextField *view in textFields) {
if ([view isFirstResponder]) {
focusView = view;
break;
}
}
if (focusView) {
//获取键盘弹出的时间
double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//获取键盘上端Y坐标
CGFloat keyboardY = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
//获取输入框下端相对于window的Y坐标
CGRect rect = [focusView convertRect:focusView.bounds toView:[[[UIApplication sharedApplication] delegate] window]];
CGPoint tmp = rect.origin;
CGFloat inputBoxY = tmp.y + focusView.frame.size.height;
//计算二者差值
CGFloat ty = keyboardY - inputBoxY;
NSLog(@"position keyboard: %f, inputbox: %f, ty: %f", keyboardY, inputBoxY, ty);
//差值小于0,做平移变换
[UIView animateWithDuration:duration animations:^{
if (ty < 0) {
self.view.transform = CGAffineTransformMakeTranslation(0, ty);
}
}];
}
}
//键盘回收
- (void)keyboardWillHide:(NSNotification *)notification
{
//获取键盘弹出的时间
double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//还原
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, 0);
}];
}
将需要随键盘上移的控件存入数组
NSArray *textFields = @[_people_num, _scale,_leader_name,_leader_phoneNum];
给tableView添加点击手势
//给tableView添加手势. 在tableView处添加以下代码
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyBoard)];
tapGestureRecognizer.cancelsTouchesInView = NO;//设置成NO表示当前控件响应后会传播到其他控件上,默认为YES。
[self.tableView addGestureRecognizer:tapGestureRecognizer];
//点击事件
-(void)hideKeyBoard
{
[self.view endEditing:YES];
}