-(void)keyboardChange:(NSNotification*)notice { NSValue *value = [[notice userInfo] objectForKey:@"UIKeyboardFrameEndUserInfoKey"]; float keyEnd_y = [value CGRectValue].origin.y; float animationDuration = [[notice userInfo][@"UIKeyboardAnimationDurationUserInfoKey"] floatValue]; CGRect frame = [[UIScreen mainScreen]bounds];//屏幕尺寸 int SCREEN_WIDTH = frame.size.width; int SCREEN_HEIGHT = frame.size.height; if(!shouldResignFirstResponder){ UIView *alphaCoverView = [[[UIApplication sharedApplication].delegate window] viewWithTag:10001]; if (!alphaCoverView) { alphaCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, keyEnd_y - 40)]; [alphaCoverView setBackgroundColor:[UIColor blackColor]]; alphaCoverView.alpha = 0.0; alphaCoverView.tag = 10001; UITapGestureRecognizer *tapToResignirstResponder = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textFielfWillResignFirstResponder)]; [alphaCoverView addGestureRecognizer:tapToResignirstResponder]; [[[UIApplication sharedApplication].delegate window] addSubview:alphaCoverView]; } [UIView animateWithDuration:animationDuration animations:^{ alphaCoverView.alpha = 0.4; alphaCoverView.frame = CGRectMake(0, 0, SCREEN_WIDTH, keyEnd_y - 40);//40是编辑框视图的高 }]; } float constant = 0.0; if (shouldResignFirstResponder) { //收回键盘时,将约束的值复原 constant = SCREEN_HEIGHT - keyEnd_y; [UIView animateWithDuration:animationDuration animations:^{ _m_spaceToBottom.constant = constant; [self.view layoutIfNeeded]; }]; shouldResignFirstResponder = NO; }else{ constant = SCREEN_HEIGHT - keyEnd_y-46;//46是编辑框距离屏幕底部的距离 [UIView animateWithDuration:animationDuration animations:^{ _m_spaceToBottom.constant = constant; [self.view layoutIfNeeded]; }]; } } - (void)textFielfWillResignFirstResponder{ UIView *view = [[[UIApplication sharedApplication].delegate window] viewWithTag:10001]; [view removeFromSuperview]; shouldResignFirstResponder = YES; [self.view endEditing:YES]; }
//键盘变化监听 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:@"UIKeyboardWillChangeFrameNotification" object:nil];
借鉴文章: