Skip to content

Instantly share code, notes, and snippets.

@bhrott
Created May 3, 2018 23:51
Show Gist options
  • Save bhrott/2b91a23bd28ed0e4a3667ffd26935caf to your computer and use it in GitHub Desktop.
Save bhrott/2b91a23bd28ed0e4a3667ffd26935caf to your computer and use it in GitHub Desktop.
Xamarin iOS: Handle keyboard with UIScrollView
public class KeyboardHelper
{
private UIViewController _viewController;
private UIScrollView _scrollView;
public KeyboardHelper(UIViewController viewController)
{
this._viewController = viewController;
}
public KeyboardHelper(UIViewController viewController, UIScrollView scrollView)
{
this._viewController = viewController;
this._scrollView = scrollView;
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, (notif) =>
{
this.OnKeyboardDidShow(notif);
});
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, (notif) =>
{
this.OnKeyboardWillHide(notif);
});
}
public void DismissKeyBoardWhenTapOutsideResponder()
{
var tapGesture = new UITapGestureRecognizer((obj) =>
{
this.DismissKeyboard();
});
this._viewController.View.AddGestureRecognizer(tapGesture);
if (this._scrollView != null)
{
this._scrollView.KeyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag;
}
}
public void DismissKeyboard()
{
this._viewController.View.EndEditing(true);
}
private void OnKeyboardDidShow(NSNotification notification)
{
var keyboardFrame = ((NSValue)notification.UserInfo[UIKeyboard.FrameEndUserInfoKey]).CGRectValue;
this._scrollView.ContentInset = new UIEdgeInsets(new nfloat(0), new nfloat(0), keyboardFrame.Height + 20, new nfloat(0.0));
}
private void OnKeyboardWillHide(NSNotification notification)
{
this._scrollView.ContentInset = UIEdgeInsets.Zero;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment