Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public static class Extensions
{
public static UIView FirstResponder (this UIView view)
{
if (view.IsFirstResponder)
return view;
foreach (var child in view.Subviews)
{
var fs = child.FirstResponder ();
if (fs != null)
return fs;
}
return null;
}
}
public override void ViewWillDisappear (bool animated)
{
base.ViewWillDisappear (animated);
UnregisterNotifications ();
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
this.scrollView.ContentSize = new SizeF (320, 400);
RegisterNotifications ();
}
NSObject _keyboardWillShow;
NSObject _keyboardWillHide;
protected void RegisterNotifications ()
{
_keyboardWillShow = NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, WillShow);
_keyboardWillHide = NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, WillHide);
}
protected void UnregisterNotifications ()
{
NSNotificationCenter.DefaultCenter.RemoveObserver (_keyboardWillShow);
NSNotificationCenter.DefaultCenter.RemoveObserver (_keyboardWillHide);
}
protected void WillShow (NSNotification notification)
{
var activeView = this.View.FirstResponder ();
if (activeView == null)
return;
//get keyboard bounds
var keyboardBounds = UIKeyboard.FrameBeginFromNotification (notification);
var contentInsets = new UIEdgeInsets (0.0f, 0.0f, keyboardBounds.Size.Height, 0.0f);
scrollView.ContentInset = contentInsets;
scrollView.ScrollIndicatorInsets = contentInsets;
//get the are above the keyboard
var areaVisibleAboveKeyboard = new RectangleF (this.View.Frame.Location,
new SizeF (this.View.Frame.Width, this.View.Frame.Size.Height - keyboardBounds.Size.Height));
//get the area of the view we want to ensure its visible
var areaActiveView = activeView.Superview.ConvertRectToView (activeView.Frame, this.View);
//if we can't see the full view, then scroll so its visible
if (!areaVisibleAboveKeyboard.Contains (areaActiveView))
{
var scrollPoint = new PointF (0.0f, areaActiveView.Location.Y + areaActiveView.Height +
scrollView.ContentOffset.Y - areaVisibleAboveKeyboard.Height);
scrollView.SetContentOffset (scrollPoint, true);
}
}
protected void WillHide (NSNotification notification)
{
var activeView = this.View.FirstResponder ();
if (activeView == null)
return;
//scroll back
var animationDuration = UIKeyboard.AnimationDurationFromNotification (notification);
var contentInsets = new UIEdgeInsets (0.0f, 0.0f, 0.0f, 0.0f);
UIView.Animate (animationDuration, delegate {
scrollView.ContentInset = contentInsets;
scrollView.ScrollIndicatorInsets = contentInsets;
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.