Created
October 27, 2015 05:47
-
-
Save Vaikesh/44e67ab680a776ef564d to your computer and use it in GitHub Desktop.
Handle keyboard show/hide in Xamarin.iOS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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