且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS 上 Xamarin.Forms 中的键盘重叠编辑器

更新时间:2023-02-03 14:39:21

您可以创建一个自定义的 iOS 渲染器,而不是使用滚动视图,当键盘处于活动状态时向上移动您的视图(使用边距).

Rather than using a scrollview, you could create a custom iOS renderer that shifts your view up (using the margin) when the keyboard is active.

一个例子可以在这里看到:https://github.com/rdelrosario/ChatUIXForms/blob/master/ChatUIXForms.iOS/Renderers/ChatEntryRenderer.cs

An example of this can be seen here: https://github.com/rdelrosario/ChatUIXForms/blob/master/ChatUIXForms.iOS/Renderers/ChatEntryRenderer.cs

相关代码:

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

    void OnKeyboardShow(object sender, UIKeyboardEventArgs args)
    {

        NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey));
        CGSize keyboardSize = result.RectangleFValue.Size;
        if (Element != null)
        {
            Element.Margin = new Thickness(0, 0, 0, keyboardSize.Height); //push the entry up to keyboard height when keyboard is activated

        }
    }

    void OnKeyboardHide(object sender, UIKeyboardEventArgs args)
    {
        if (Element != null)
        {
            Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed
        }

    }


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

        if (_keyboardHideObserver != null)
        {
            _keyboardHideObserver.Dispose();
            _keyboardHideObserver = null;
        }
    }

在 Android 上,这可能不是问题,但如果是,您可以尝试

On Android, it's likely not an issue, but if it is, you could try

android:Application.WindowSoftInputModeAdjust="Resize"