Sgt Maddonut
Sgt Maddonut

Reputation: 779

Keyboard overlaps Editor in Xamarin.Forms on iOS

When I focus that Editor, a keyboard overlaps Editor and Button. I know, there is a solution: putting elements inside ScrollView, but this solution makes huge problems with scrolling ListView inside ScrollView. What should I do, to make it work properly?

Layout: red - ScrollView, green - ListView, blue - StackLayout with Editor and Button.

enter image description here

Here is the video how this works: https://streamable.com/wvd3h

Solution #2 is to use Xamarin.Forms.Plugins - KeyboardOverlap, but this plugin has a problem with tab bar on TabbedPage

Upvotes: 2

Views: 1441

Answers (1)

Ben Reierson
Ben Reierson

Reputation: 1099

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.

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

Relevant code:

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;
        }
    }

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

android:Application.WindowSoftInputModeAdjust="Resize"

Upvotes: 3

Related Questions