Sunday, February 10, 2013

キーボード表示時にリサイズ

キーボード表示時にUITextViewをリサイズするテンプレ

Landscapeの場合keyboardRectのwidthとheightが逆になるので考慮する
self.viewのサイズを取得する場合はboundsを使用する。(frameの場合Landscapeになっても値が変わらない)

- (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*)notification
{
 CGRect keyboardRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
 if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
  CGRect rect = keyboardRect;
  rect.size.width = keyboardRect.size.height;
  rect.size.height = keyboardRect.size.width;
  keyboardRect = rect;
 }
 CGRect frame = self.textView.frame;
 frame.size.height = self.view.bounds.size.height - keyboardRect.size.height;
  
 NSTimeInterval duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
 
 UIViewAnimationCurve curve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
 
 [UIView animateWithDuration:duration delay:0.0f options:(curve << 16) animations:^{
  self.textView.frame = frame;
 } completion:nil];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
 CGRect frame = self.textView.frame;
 frame.size.height = self.view.bounds.size.height;
 
 NSTimeInterval duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
 
 UIViewAnimationCurve curve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
 
 [UIView animateWithDuration:duration delay:0.0f options:(curve << 16) animations:^{
  self.textView.frame = frame;
 } completion:nil];
}

No comments:

Post a Comment