//页面加载前调用的方法,注册两个通知:一个是键盘弹出来的通知,另外一个是键盘隐藏的通知,不同的通知调用不同的方法进行处理
-(void)viewWillAppear:(BOOL)animated
{
// 注册键盘的通知中心 当键盘出现或改变的时候
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
// //当键盘将要消失的时候
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHiden:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark 通知
-(void)keyboardWillShow:(NSNotification *)notification
{
//获取键盘的frame
CGRect keyboardRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//当前键盘的高度 和宽度
int keyHeight = keyboardRect.size.height;
int keyHwidth = keyboardRect.size.width;
//获取系统键盘的动画时间,这样可以在视图上移的时候更连贯
double duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//距离 = 键盘顶端的坐标y值 与 键盘以上的长度进行比较
int offSet =CGRectGetMaxY(self.currentTextField.frame) -( self.view.frame.size.height - keyHeight);
if (offSet > 0) {
[UIView animateWithDuration:0.25f animations:^{ //需要操作的动画效果 已什么样的形式 显示
self.view.frame = CGRectMake(0, -offSet, CGRectGetWidth(self.view.frame),CGRectGetHeight(self.view.frame));
}];
}
}
-(void)keyboardWillHiden:(NSNotification *)notification
{
// 键盘动画时间
double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
NSLog(@"%lf",duration);
//视图下沉恢复原状
[UIView animateWithDuration:0.25f animations:^{
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}];
}
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:UIKeyboardWillShowNotification];
[[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:UIKeyboardWillHideNotification];
}
//下面两句话必须写,否则scrollView不可以动
self.myscrollView.frame =CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
[self.myscrollView setContentSize:CGSizeMake(CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)+44)];
//在这里要注意 点击的第一响应者是scrollView 所以点击不到TextField 添加一个手势
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchScrollView)];
//轻击 的次数
[recognizer setNumberOfTapsRequired:1];
//需要的手指 次数
[recognizer setNumberOfTouchesRequired:1];
[self.myscrollView addGestureRecognizer:recognizer];
}
-(void)touchScrollView{
[self.userTextField resignFirstResponder];
[self.loginTextField resignFirstResponder];
[self.thirdTextField resignFirstResponder];
}