介绍:不论是UITextField,还是UITextView,使用它们输入文字时都是有键盘的弹出,此时可能会挡住我们创建的一分部其他视图,此时,就需要根据键盘的高度将我们被隐藏的部分View做向上或者向下平移,使用tansform或者动画UIViewAnimation均可,使用如下:
这是跟键盘有关的所有通知:
//键盘显示和隐藏 UIKIT_EXTERN NSString *const UIKeyboardWillShowNotification; UIKIT_EXTERN NSString *const UIKeyboardDidShowNotification; UIKIT_EXTERN NSString *const UIKeyboardWillHideNotification; UIKIT_EXTERN NSString *const UIKeyboardDidHideNotification;
//键盘弹出后,通过这个key可以取出需要的键盘的frame,我们就是通过这frame的高度来做平移的 UIKIT_EXTERN NSString *const UIKeyboardFrameBeginUserInfoKey NS_AVAILABLE_IOS(3_2); // NSValue of CGRect UIKIT_EXTERN NSString *const UIKeyboardFrameEndUserInfoKey NS_AVAILABLE_IOS(3_2); // NSValue of CGRect UIKIT_EXTERN NSString *const UIKeyboardAnimationDurationUserInfoKey NS_AVAILABLE_IOS(3_0); // NSNumber of double UIKIT_EXTERN NSString *const UIKeyboardAnimationCurveUserInfoKey NS_AVAILABLE_IOS(3_0); // NSNumber of NSUInteger (UIViewAnimationCurve) UIKIT_EXTERN NSString *const UIKeyboardIsLocalUserInfoKey NS_AVAILABLE_IOS(9_0); // NSNumber of BOOL //键盘将要改变时的通知 UIKIT_EXTERN NSString *const UIKeyboardWillChangeFrameNotification NS_AVAILABLE_IOS(5_0); UIKIT_EXTERN NSString *const UIKeyboardDidChangeFrameNotification NS_AVAILABLE_IOS(5_0); // These keys are superseded by UIKeyboardFrameBeginUserInfoKey and UIKeyboardFrameEndUserInfoKey. UIKIT_EXTERN NSString *const UIKeyboardCenterBeginUserInfoKey NS_DEPRECATED_IOS(2_0, 3_2) __TVOS_PROHIBITED; UIKIT_EXTERN NSString *const UIKeyboardCenterEndUserInfoKey NS_DEPRECATED_IOS(2_0, 3_2) __TVOS_PROHIBITED; UIKIT_EXTERN NSString *const UIKeyboardBoundsUserInfoKey NS_DEPRECATED_IOS(2_0, 3_2) __TVOS_PROHIBITED;
demo:
//注册通知
//首先在ViewDidload中添加对键盘通知的监听 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//键盘将要显示
-(void)keyboardWillShow:(NSNotification *)notification { //NSLog(@"keyboardWillShow:%@",notification); NSDictionary *userInfo = [notification userInfo]; CGFloat duration = [[userInfo objectForKey:@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue]; CGRect rect = [[userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"]CGRectValue]; [UIView animateWithDuration:duration animations:^{ self.view.transform = CGAffineTransformMakeTranslation(0, -(SCREEN_HEIGHT-rect.origin.y)); }]; }
//键盘将要隐藏
-(void)keyboardWillHide:(NSNotification *)notification { //NSLog(@"keyboardWillHide:%@",notification); NSDictionary *userInfo = [notification userInfo]; CGFloat duration = [[userInfo objectForKey:@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue]; [UIView animateWithDuration:duration animations:^{ self.view.transform = CGAffineTransformIdentity; }]; }