我有一个UITextField,我放在屏幕的底部:
通常这个文本字段会被键盘隐藏,但我遵循了以下组合:
并创建了我的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
关于我可能做错了什么的想法?
答案 0 :(得分:1)
显示键盘时,您应该修改视图的高度。
这样的事情:
var frame = View.Frame;
frame.Height -= keyboardHeight;
View.Frame = frame;
获取键盘高度:
bool isLandscape = InterfaceOrientation == UIInterfaceOrientation.LandscapeLeft || InterfaceOrientation == UIInterfaceOrientation.LandscapeRight;
var keyboardFrame = UIKeyboard.FrameEndFromNotification (notification);
var keyboardHeight = isLandscape ? keyboardFrame.Width : keyboardFrame.Height;
只要您UITextField
的{{1}}设置为中心,那么您的用户界面就应该正确。