- (void)addKeyboardShowViewChange {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- 处理键盘将要显示消息
- keyboardSubView 为获取到的触发键盘相应的View
- keyboardChangeHeight 为VC改变的高度
- (void)keyboardWillShow:(NSNotification *)notification {
self.keyboardSubView = nil;
[self getSubViewWith:[self visibleViewController].view];
if (self.keyboardSubView) {
CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect startRact = [self.keyboardSubView convertRect:self.keyboardSubView.bounds toView:[UIApplication sharedApplication].keyWindow];
NSLog(@"%lf %lf %lf",startRact.origin.y,startRact.size.height,frame.size.height);
if (kHeight-startRact.origin.y-startRact.size.height > frame.size.height ) {
self.keyboardChangeHeight = 0;
} else {
self.keyboardChangeHeight = frame.size.height - (kHeight-startRact.origin.y-startRact.size.height);
[UIApplication sharedApplication].keyWindow.rootViewController.view.frame = CGRectMake(0, -self.keyboardChangeHeight, kWidth, kHeight);
}
}
}
- (void)getSubViewWith:(UIView *)view {
for (UIView *subView in view.subviews) {
if ([subView isKindOfClass:[UITextField class]]) {
if ([subView isFirstResponder]) {
self.keyboardSubView = subView;
return;
}
} else if ([subView isKindOfClass:[UITextView class]]) {
if ([subView isFirstResponder]) {
self.keyboardSubView = subView;
return;
}
} else {
[self getSubViewWith:subView];
}
}
}
- (void)keyboardWillHidden:(NSNotification *)notification {
if (self.keyboardChangeHeight > 0) {
[UIApplication sharedApplication].keyWindow.rootViewController.view.frame = CGRectMake(0, 0, kWidth, kHeight);
self.keyboardChangeHeight = 0;
}
self.keyboardSubView = nil;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
单例全局处理键盘事件
单例处理代码链接