Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dataich/356516 to your computer and use it in GitHub Desktop.
Save dataich/356516 to your computer and use it in GitHub Desktop.
@interface CustomViewController : UIViewController <UITextViewDelegate> {
UITextView *_textView; //対象となるテキストビュー。UIViewControllerのサブビューとして追加する。
}
@property (nonatomic, retain) IBOutlet UITextView *_textView;
@end
@implementation CustomViewController
- (void)viewDidLoad {
[super viewDidLoad];
//親ビューの高さが変更された時に追従するようにする
_textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//キーボード表示・非表示の通知の開始
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
//キーボード表示・非表示の通知を終了
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
//キーボードが表示された場合
- (void)keyboardWillShow:(NSNotification *)aNotification {
//キーボードのCGRectを取得
CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [[self.view superview] convertRect:keyboardRect fromView:nil];
//キーボードのanimationDurationを取得
NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//メインビューの高さをキーボードの高さ分マイナスしたframe
CGRect frame = self.view.frame;
frame.size.height -= keyboardRect.size.height;
//キーボードアニメーションと同じ間隔でメインビューの高さをアニメーションしつつ変更する。
//これでUITextViewも追従して高さが変わる。
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
}
//キーボードが非表示にされた場合(keyboardWillShowと同じことを高さを+してやっているだけ)
- (void)keyboardWillHide:(NSNotification *)aNotification {
CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [[self.view superview] convertRect:keyboardRect fromView:nil];
NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect frame = self.view.frame;
frame.size.height += keyboardRect.size.height;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
self.view.frame = frame;
[UIView commitAnimations];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment