如何防止键盘覆盖我的UI而不是调整其大小?

Ant*_*lls 14 ios xamarin.forms

在iOS中,当根节点为a时键盘出现时,Xamarin.Forms会调整屏幕大小ScrollView.但是当根节点不是ScrollView键盘时,隐藏了UI的一部分.你如何防止这种情况发生?

Ant*_*lls 24

修复此问题的方法是使用自定义渲染器来侦听显示的键盘,并在其中添加填充.

在您的PCL项目中,KeyboardResizingAwareContentPage.cs:

using Xamarin.Forms;

public class KeyboardResizingAwareContentPage : ContentPage {
    public bool CancelsTouchesInView = true;
}
Run Code Online (Sandbox Code Playgroud)

在您的iOS项目中,IosKeyboardFixPageRenderer.cs:

using Foundation;
using MyProject.iOS.Renderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(KeyboardResizingAwareContentPage), typeof(IosKeyboardFixPageRenderer))]

namespace MyProject.iOS.Renderers {
    public class IosKeyboardFixPageRenderer : PageRenderer {
        NSObject observerHideKeyboard;
        NSObject observerShowKeyboard;

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var cp = Element as KeyboardResizingAwareContentPage;
            if (cp != null && !cp.CancelsTouchesInView) {
                foreach (var g in View.GestureRecognizers) {
                    g.CancelsTouchesInView = false;
                }
            }
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            observerHideKeyboard = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, OnKeyboardNotification);
            observerShowKeyboard = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, OnKeyboardNotification);
        }

        public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);

            NSNotificationCenter.DefaultCenter.RemoveObserver(observerHideKeyboard);
            NSNotificationCenter.DefaultCenter.RemoveObserver(observerShowKeyboard);
        }

        void OnKeyboardNotification(NSNotification notification)
        {
            if (!IsViewLoaded) return;

            var frameBegin = UIKeyboard.FrameBeginFromNotification(notification);
            var frameEnd = UIKeyboard.FrameEndFromNotification(notification);

            var page = Element as ContentPage;
            if (page != null && !(page.Content is ScrollView)) {
                var padding = page.Padding;
                page.Padding = new Thickness(padding.Left, padding.Top, padding.Right, padding.Bottom + frameBegin.Top - frameEnd.Top);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我来自Xamarin论坛.我非常感谢你的代码.:) (3认同)