Skip to content

Instantly share code, notes, and snippets.

@Vaikesh
Created October 27, 2015 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vaikesh/44e67ab680a776ef564d to your computer and use it in GitHub Desktop.
Save Vaikesh/44e67ab680a776ef564d to your computer and use it in GitHub Desktop.
Handle keyboard show/hide in Xamarin.iOS.
NSObject keyboardShowObserver;
NSObject keyboardHideObserver;
public override void ViewWillAppear(bool animated) {
base.ViewWillAppear(animated);
keyboardShowObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, (notification) => {
NSValue nsKeyboardBounds = (NSValue)notification.UserInfo.ObjectForKey(UIKeyboard.BoundsUserInfoKey);
RectangleF keyboardBounds = nsKeyboardBounds.RectangleFValue;
float height = View.Bounds.Height - keyboardBounds.Height;
if (NavigationController != null && NavigationController.TabBarController != null && NavigationController.TabBarController.TabBar != null) {
// Re-add tab bar height since it is hidden under keyboard but still excluded from View.Bounds.Height.
height += NavigationController.TabBarController.TabBar.Frame.Height;
}
someScrollView.Frame = new RectangleF(someScrollView.Frame.Location, new SizeF(View.Bounds.Width, height));
});
keyboardHideObserver = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, (notification) => {
UIApplication.EnsureUIThread();
someScrollView.Frame = new RectangleF(someScrollView.Frame.Location, View.Bounds.Size);
});
}
public override void ViewDidDisappear(bool animated) {
base.ViewDidDisappear(animated);
if (keyboardShowObserver != null) {
NSNotificationCenter.DefaultCenter.RemoveObserver(keyboardShowObserver);
}
if (keyboardHideObserver != null) {
NSNotificationCenter.DefaultCenter.RemoveObserver(keyboardHideObserver);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment