//注册键盘出现的通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeShown:)
name:UIKeyboardWillShowNotification object:nil];
//注册键盘消失的通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
//点击任一一处,键盘消失
[self setUpForDismissKeyboard];
#pragma mark - 推出键盘屏幕上移
- (void)keyboardWillBeShown:(NSNotification *)notification {
CGSize keyboardSize = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; // 获取键盘的Size
//self.keyboardHeight = keyboardSize.height/3.5;
[UIView animateWithDuration:0.30 animations:^{
if (KScreenHeight < 667) {
self.view.frame = CGRectMake(0, -keyboardSize.height/2, KScreenWidth, KScreenWidth);
} else {
self.view.frame = CGRectMake(0, -keyboardSize.height/2, KScreenWidth, KScreenHeight);
}
}];
// _keyboardHasShown = YES;
}
- (void)keyboardWillBeHidden:(NSNotification *)notification{
[UIView animateWithDuration:0.30 animations:^{
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
// self.iconView.hidden = NO;
}];
// _keyboardHasShown = NO;
}
#pragma mark - 点击屏幕任意一处隐藏键盘
- (void)setUpForDismissKeyboard {
UITapGestureRecognizer *singleTapGR =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tapAnywhereToDismissKeyboard:)];
NSOperationQueue *mainQuene = [NSOperationQueue mainQueue];
__weak typeof(self)weakSelf = self;
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification
object:nil
queue:mainQuene
usingBlock:^(NSNotification *note){
[weakSelf.view addGestureRecognizer:singleTapGR];
}];
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification
object:nil
queue:mainQuene
usingBlock:^(NSNotification *note){
[weakSelf.view removeGestureRecognizer:singleTapGR];
}];
}
- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
//此method会将self.view里所有的subview的first responder都resign掉
[self.view endEditing:YES];
}
- (void) viewDidUnload //dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
// [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIKeyboardWillShowNotification" object:nil];
//
// [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIKeyboardWillHideNotification" object:nil];
}
网友评论