以前にここで答えを見つけましたが、コードを追加して、ユーザーが地球キー(
YourViewController.h で、キーボードの高さ (表示されている場合のみ) をインスタンス変数に格納します。
@interface YourViewController : UIViewController {
CGFloat keyboardHeightIfShowing ;
}
YourViewController.m で、これらのメソッドを実装します。
- (void) keyboardWillShow:(NSNotification*)notification {
[self moveTextViewForKeyboard:notification up:YES] ;
}
- (void) keyboardWillHide:(NSNotification*)notification {
[self moveTextViewForKeyboard:notification up:NO] ;
}
- (void) moveTextViewForKeyboard:(NSNotification*)notification up:(BOOL)up {
NSDictionary* userInfo = [notification userInfo] ;
UIViewAnimationCurve animationCurve ;
NSTimeInterval animationDuration ;
CGRect keyboardEndFrame ;
[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve] ;
[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration] ;
[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame] ;
[UIView beginAnimations:nil context:nil] ;
[UIView setAnimationDuration:animationDuration] ;
[UIView setAnimationCurve:animationCurve] ;
CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame toView:nil] ;
//Since I have a UITabBar, when the keyboard appears, self.view.frame.height should shrink by slightly less than if I did not have a UITabBar.
keyboardFrame.size.height -= self.tabBarController.tabBar.frame.size.height ;
CGRect newViewFrame = self.view.frame ;
//UIKeyboardWillShowNotification can be triggered even when the keyboard is already showing, such as when switching between certain international keyboards. When this happens, before shrinking newViewFrame to accommodate keyboardFrame, enlarge newViewFrame so that it is the size it was before the previous keyboard appeared.
if ( up && keyboardHeightIfShowing ) {
NSLog(@"hiding keyboard with height %0.1f, showing keyboard with height %0.1f",keyboardHeightIfShowing, keyboardFrame.size.height) ;
newViewFrame.size.height += keyboardHeightIfShowing ;
}
newViewFrame.size.height -= keyboardFrame.size.height * (up ? 1 : -1) ;
keyboardHeightIfShowing = ( up ? keyboardFrame.size.height : 0 ) ;
self.view.frame = newViewFrame ;
[UIView commitAnimations] ;
}
そして最後に、YourViewController.m で確立keyboardWillShow
しkeyboardWillHide
、UIKeyboardWillShow/Hide 通知によって呼び出されるようにします。
- (void) viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil] ;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil] ;
}
- (void) viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil] ;
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil] ;
}