MAUI IOS如何弹起键盘时调整页面大小

#if IOS
using CoreGraphics;
using Foundation;
using Microsoft.Maui.Platform;
using UIKit;
#endif

namespace YourProject
{
#nullable disable
    public class MainPage
    {
	    public MainPage()
        {
            InitializeComponent();
#if IOS
            Initialize();
#endif
        }
#if IOS
        double paddingBottom = 0;

        bool showSoftKeyboard;

        NSObject _keyboardShowObserver;

        NSObject _keyboardHideObserver;

        ~MainPage()
        {
            UnregisterForKeyboardNotifications();
        }

        void Initialize()
        {
            this.Padding = new(Padding.Left, Padding.Top, Padding.Right, paddingBottom);
            RegisterForKeyboardNotifications();
        }

        // On the iOS platform, adjust the window size when the soft keyboard pops up
        // https://github.com/dotnet/maui/issues/10662
        void OnKeyboardShow(object sender, UIKeyboardEventArgs args)
        {
            if (showSoftKeyboard)
            {
                return;
            }

            showSoftKeyboard = true;
            NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey));
            CGSize keyboardSize = result.RectangleFValue.Size;

            paddingBottom = this.Padding.Bottom;
            this.Padding = new Thickness(Padding.Left, Padding.Top, Padding.Right, keyboardSize.Height);
        }

        void OnKeyboardHide(object sender, UIKeyboardEventArgs args)
        {
            if (!showSoftKeyboard)
            {
                return;
            }

            showSoftKeyboard = false;

            this.Padding = new Thickness(Padding.Left, Padding.Top, Padding.Right, paddingBottom);
        }

        void RegisterForKeyboardNotifications()
        {
            _keyboardShowObserver ??= UIKeyboard.Notifications.ObserveWillShow(OnKeyboardShow);
            _keyboardHideObserver ??= UIKeyboard.Notifications.ObserveWillHide(OnKeyboardHide);
        }

        void UnregisterForKeyboardNotifications()
        {
            if (_keyboardShowObserver is not null)
            {
                _keyboardShowObserver.Dispose();
                _keyboardShowObserver = null;
            }

            if (_keyboardHideObserver is not null)
            {
                _keyboardHideObserver.Dispose();
                _keyboardHideObserver = null;
            }
        }
#endif
    }
}
posted @   Yu-Core  阅读(13)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示