Modifying UIScrollView height when keyboard appears

When the keyboard appears over a UIScrollView (that includes the UITableView) the content underneath the keyboard isn’t accessible unless you change the height of the frame of the UIScrollView. Here’s how to do that in MonoTouch.

private NSObject _keyboardShowObserver;
private NSObject _keyboardHideObserver;

// this method assumes the height of a navigation bar on top
// hence the 44 pixels
public override void ViewWillAppear (bool animate)
{
  base.ViewWillAppear (animate);
  
  _keyboardShowObserver = NSNotificationCenter.DefaultCenter
    .AddObserver(UIKeyboard.WillShowNotification, (notification) => {
      var keyboardBounds = (NSValue)notification
        .UserInfo.ObjectForKey(UIKeyboard.BoundsUserInfoKey);
      var keyboardSize = keyboardBounds.RectangleFValue;
    
      UIView.BeginAnimations("k");
      UIView.SetAnimationBeginsFromCurrentState(true);
      _scrollView.Frame = new RectangleF(0, 44, View.Frame.Width, 
        View.Frame.Height - keyboardSize.Height - 44);
      UIView.CommitAnimations();
    });

  _keyboardHideObserver = NSNotificationCenter.DefaultCenter
    .AddObserver(UIKeyboard.WillHideNotification, (notification) => {
      UIView.BeginAnimations("k");
      UIView.SetAnimationBeginsFromCurrentState(true);
      _scrollView.Frame = new RectangleF(0, 44, 
        View.Frame.Width, View.Frame.Height - 44);
      UIView.CommitAnimations();
    });
}

// and don't forget to remove the observers on disappear
public override void ViewWillDisappear(bool animate)
{
  base.ViewWillDisappear(animate);
  NSNotificationCenter.DefaultCenter.RemoveObserver(_keyboardHideObserver);
  NSNotificationCenter.DefaultCenter.RemoveObserver(_keyboardShowObserver);
}
Advertisements

4 Responses to Modifying UIScrollView height when keyboard appears

  1. DZ says:

    This tidbit was absolutely AWESOME to find. Thank you!

  2. Alan Kell says:

    Very useful piece of code – thankyou very much!

  3. This is amazing. Thanks!

  4. David says:

    Fantastic, really helped me, thank you very much.

    A note to anyone reading this who created the UIScrollView in the designer (not in code), this line will not work:

    _scrollView.Frame = new RectangleF(0, 44, View.Frame.Width,
    View.Frame.Height – keyboardSize.Height – 44);

    To get round this, I created and and populated the UIViewScroll in code (which was a pain but works good now).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: