iOS相关
有两种方法可以实现这个功能!
第一种方法:如果你的应用程序很小,只需为一个UIViewController实现以下步骤即可:
步骤1:添加用于显示和隐藏观察者的字段:
private NSObject _keyboardObserverWillShow;
private NSObject _keyboardObserverWillHide;
步骤2:更新ViewDidLoad和ViewDidUnload覆盖方法,以便在键盘显示或隐藏时添加/删除观察者:
public override void ViewDidLoad() {
base.ViewDidLoad ();
_keyboardObserverWillShow = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, KeyboardDidShowNotification);
_keyboardObserverWillHide = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, KeyboardWillHideNotification);
}
public override void ViewDidUnload() {
base.ViewDidUnload();
NSNotificationCenter.DefaultCenter.RemoveObserver(_keyboardObserverWillShow);
NSNotificationCenter.DefaultCenter.RemoveObserver(_keyboardObserverWillHide);
}
步骤三:然后您填充执行每个观察者的函数KeyboardDidShowNotification
和KeyboardWillHideNotification
。这段代码比较长,需要一些时间来解释每个部分,但您可以在评论区询问我。代码如下:
private void KeyboardWillHideNotification (NSNotification notification)
{
UIView activeView = View.FindFirstResponder();
if (activeView == null)
return;
UIScrollView scrollView = activeView.FindSuperviewOfType (this.View, typeof(UIScrollView)) as UIScrollView;
if (scrollView == null)
return;
double animationDuration = UIKeyboard.AnimationDurationFromNotification(notification);
UIEdgeInsets contentInsets = new UIEdgeInsets(0.0f, 0.0f, 0.0f, 0.0f);
UIView.Animate(animationDuration, delegate{
scrollView.ContentInset = contentInsets;
scrollView.ScrollIndicatorInsets = contentInsets;
});
}
private void KeyboardDidShowNotification (NSNotification notification)
{
UIView activeView = View.FindFirstResponder();
if (activeView == null)
return;
((UITextField)activeView).ShowDoneButtonOnKeyboard();
UIScrollView scrollView = activeView.FindSuperviewOfType(this.View, typeof(UIScrollView)) as UIScrollView;
if (scrollView == null)
return;
RectangleF keyboardBounds = UIKeyboard.BoundsFromNotification(notification);
UIEdgeInsets contentInsets = new UIEdgeInsets(0.0f, 0.0f, keyboardBounds.Size.Height, 0.0f);
scrollView.ContentInset = contentInsets;
scrollView.ScrollIndicatorInsets = contentInsets;
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);
if (!viewRectAboveKeyboard.Contains(activeFieldAbsoluteFrame)) {
PointF scrollPoint = new PointF(0.0f, activeFieldAbsoluteFrame.Location.Y + activeFieldAbsoluteFrame.Height + scrollView.ContentOffset.Y - viewRectAboveKeyboard.Height);
scrollView.SetContentOffset(scrollPoint, true);
}
}
第二种方式:创建一个键盘处理程序,通过您的BaseViewController可在每个页面上使用。
对于Android:
您可以按照StackOverflow提供的解决方案Xamarin solution here((Activity)Forms.Context).Window.SetSoftInputMode(SoftInput.AdjustPan);
进行操作。有时这不起作用,所以您可以使用此方法进行修复。PS:没有复制这些答案,因为重新编写答案没有意义。