1.添加委托UITextFieldDelegate
2.
-(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } //隐藏键盘
- (void)textFieldDidBeginEditing:(UITextField *)textField { [self animateTextField: textField up: YES]; }
- (void)textFieldDidEndEditing:(UITextField *)textField { [self animateTextField: textField up: NO]; }
- (void) animateTextField: (UITextField*) textField up: (BOOL) up { const int movementDistance = 60; // tweak as needed const float movementDuration = 0.3f; // tweak as needed int movement = (up ? -movementDistance : movementDistance); [UIView beginAnimations: @"anim" context: nil]; [UIView setAnimationBeginsFromCurrentState: YES]; [UIView setAnimationDuration: movementDuration]; self.view.frame = CGRectOffset(self.view.frame, 0, movement); [UIView commitAnimations]; }
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil]; #pragma mark - 键盘处理 #pragma mark 键盘即将显示 - (void)keyBoardWillShow:(NSNotification *)note{ CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGFloat ty = - rect.size.height; [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{ self.view.transform = CGAffineTransformMakeTranslation(0, ty + kNavigationBarHeight); }]; } #pragma mark 键盘即将退出 - (void)keyBoardWillHide:(NSNotification *)note{ [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{ self.view.transform = CGAffineTransformIdentity; }]; }