#pragma mark - 键盘处理
#pragma mark 监听系统发出的键盘通知
- (void)addKeyboardNote {
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
// 1.显示键盘
[center addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
// 2.隐藏键盘
[center addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark 键盘通知监听
- (void)keyboardChange:(NSNotification *)note {
NSDictionary *userInfo = note.userInfo;
NSTimeInterval duration;
CGRect keyboardF;
[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardF];
//保护
if (duration <= 0.0) {
duration = 0.25;
}
//取得当前聚焦文本框不想被遮挡控件的frame
CGRect frame = self.lab.frame;
//找到不想被遮挡的最大Y
CGFloat maxY = CGRectGetMaxY(frame);
//取出差距(键盘最小Y - 防遮挡控件的最大Y)
CGFloat transformY = CGRectGetMinY(keyboardF) - maxY;
[UIView animateWithDuration:duration animations:^{
if (transformY < 0) { //挡住了
self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
} else { // 没有挡住
self.view.transform = CGAffineTransformIdentity;
}
}];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}