#pragma mark - 键盘处理
#pragma mark 监听系统发出的键盘通知
- (void)addKeyboardNote
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
// 1.显示键盘
[center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
// 2.隐藏键盘
[center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark 显示一个新的键盘就会调用
- (void)keyboardWillShow:(NSNotification *)note
{
// 1.取得当前聚焦文本框最下面的Y值
CGFloat loginBtnMaxY = CGRectGetMaxY(loginBtn.frame);
// 2.取出键盘的高度
CGFloat keyboardH = [note.userInfo [UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
// 3.控制器view的高度 - 键盘的高度
CGFloat keyboardY = self.view.frame.size.height - keyboardH;
// 4.比较登录按钮最大Y 跟 键盘Y
CGFloat duration = [note.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
if (duration <= 0.0) {
duration = 0.25;
}
[UIView animateWithDuration:duration animations:^{
if (loginBtnMaxY > keyboardY) { // 键盘挡住了登录按钮
self.view.transform = CGAffineTransformMakeTranslation(0, keyboardY - loginBtnMaxY - 8);
} else { // 没有挡住登录按钮
self.view.transform = CGAffineTransformIdentity;
}
}];
}
#pragma mark 隐藏键盘就会调用
- (void)keyboardWillHide:(NSNotification *)note
{
CGFloat duration = [note.userInfo [UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[UIView animateWithDuration:duration animations:^{
self.view.transform = CGAffineTransformIdentity;
}];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
网友评论