有时您不能将主视图放在滚动视图中,在这种情况下,您可以通过处理 iOS 项目的键盘事件并将它们传递到表单级别来实现这一点。Android 会照顾好自己。
using System;
using Foundation;
using UIKit;
using RaiseKeyboard.iOS;
[assembly: Xamarin.Forms.Dependency (typeof (KeyboardHelper))]
namespace RaiseKeyboard.iOS
{
// Raises keyboard changed events containing the keyboard height and
// whether the keyboard is becoming visible or not
public class KeyboardHelper : IKeyboardHelper
{
public KeyboardHelper() {
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, OnKeyboardNotification);
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, OnKeyboardNotification);
}
public event EventHandler<KeyboardHelperEventArgs> KeyboardChanged;
private void OnKeyboardNotification (NSNotification notification)
{
var visible = notification.Name == UIKeyboard.WillShowNotification;
var keyboardFrame = visible
? UIKeyboard.FrameEndFromNotification(notification)
: UIKeyboard.FrameBeginFromNotification(notification);
if (KeyboardChanged != null) {
KeyboardChanged (this, new KeyboardHelperEventArgs (visible, (float)keyboardFrame.Height));
}
}
}
}
然后在表单级别:
using System;
using Xamarin.Forms;
namespace RaiseKeyboard
{
// Provides static access to keyboard events
public static class KeyboardHelper
{
private static IKeyboardHelper keyboardHelper = null;
public static void Init() {
if (keyboardHelper == null) {
keyboardHelper = DependencyService.Get<IKeyboardHelper>();
}
}
public static event EventHandler<KeyboardHelperEventArgs> KeyboardChanged {
add {
Init();
keyboardHelper.KeyboardChanged += value;
}
remove {
Init ();
keyboardHelper.KeyboardChanged -= value;
}
}
}
public interface IKeyboardHelper
{
event EventHandler<KeyboardHelperEventArgs> KeyboardChanged;
}
public class KeyboardHelperEventArgs : EventArgs
{
public readonly bool Visible;
public readonly float Height;
public KeyboardHelperEventArgs(bool visible, float height) {
Visible = visible;
Height = height;
}
}
}
如果您在 Stacklayout 中工作并希望将视图提升到键盘上方,您可以在堆栈底部放置一个高度为 0 的垫片。然后将其设置为键盘更改事件引发时的键盘高度。
spacer.HeightRequest = e.Visible ? e.Height : 0;
如果您正在使用 Listview,您可以通过将视图转换为重叠的数量来处理此问题。
bottomOffset = mainStack.Bounds.Bottom - textStack.Bounds.Bottom;
textStack.TranslationY -= e.Visible ? e.Height - bottomOffset : bottomOffset - e.Height;
Listviews 必须以不同的方式处理,因为高度是由 Forms 自动调整的,并且使用间隔会导致过度校正。
示例:https ://github.com/naturalistic/raisekeyboard