我有一个 UITextField 我放在我的屏幕底部:
通常这个文本字段会被键盘隐藏,但我遵循了以下组合:
- http://spazzarama.com/2011/09/07/monotouch-auto-scroll-uitextfield-or-other-views-hidden-by-keyboard/
- http://www.ashokkarunakaran.com/2012/09/08/monotouchdatepicker/
并创建了我的 UITextField ,当它被选中时会显示一个日期选择器,并且 UITextField 会自动向上滚动:
这很好用,直到我将手机旋转到横向。
一旦在风景中,我的 UITextField 被推到屏幕上太远,不再看到它。
在代码中,我订阅了 UIKeyboard.WillShowNotification 并在下面调用 KeyboardWillShowNotification:
protected virtual void KeyboardWillShowNotification (NSNotification notification)
{
UIView activeView = KeyboardGetActiveView();
if (activeView == null)
return;
UIScrollView scrollView = activeView.FindSuperviewOfType(this.View, typeof(UIScrollView)) as UIScrollView;
if (scrollView == null)
return;
RectangleF keyboardBounds = UIKeyboard.FrameBeginFromNotification(notification);
UIEdgeInsets contentInsets = new UIEdgeInsets(0.0f, 0.0f, keyboardBounds.Size.Height, 0.0f);
scrollView.ContentInset = contentInsets;
scrollView.ScrollIndicatorInsets = contentInsets;
// If activeField is hidden by keyboard, scroll it so it's visible
RectangleF viewRectAboveKeyboard = new RectangleF(this.View.Frame.Location, new SizeF(this.View.Frame.Width, this.View.Frame.Size.Height - keyboardBounds.Size.Height));
RectangleF activeFieldAbsoluteFrame = activeView.Superview.ConvertRectToView(activeView.Frame, this.View);
// activeFieldAbsoluteFrame is relative to this.View so does not include any scrollView.ContentOffset
// Check if the activeField will be partially or entirely covered by the keyboard
if (!viewRectAboveKeyboard.Contains(activeFieldAbsoluteFrame))
{
// Scroll to the activeField Y position + activeField.Height + current scrollView.ContentOffset.Y - the keyboard Height
PointF scrollPoint = new PointF(0.0f, activeFieldAbsoluteFrame.Location.Y + activeFieldAbsoluteFrame.Height + scrollView.ContentOffset.Y - viewRectAboveKeyboard.Height);
scrollView.SetContentOffset(scrollPoint, true);
}
}
两个补充功能:
protected virtual UIView KeyboardGetActiveView()
{
return this.View.FindFirstResponder();
}
public static UIView FindFirstResponder (this UIView view)
{
if (view.IsFirstResponder)
{
return view;
}
foreach (UIView subView in view.Subviews) {
var firstResponder = subView.FindFirstResponder();
if (firstResponder != null)
return firstResponder;
}
return null;
}
public static UIView FindSuperviewOfType(this UIView view, UIView stopAt, Type type)
{
if (view.Superview != null)
{
if (type.IsAssignableFrom(view.Superview.GetType()))
{
return view.Superview;
}
if (view.Superview != stopAt)
return view.Superview.FindSuperviewOfType(stopAt, type);
}
return null;
}
BitBucket 上有完整源代码:https ://bitbucket.org/benhysell/uitextfielddatepicker
关于我可能做错了什么的想法?