user-interfaceunity-game-engineunity3d-gui

How to scroll to a specific element in ScrollRect with Unity UI?


I built a registration form for a mobile game using Unity 5.1. To do that, I use Unity UI components: ScrollRect + Autolayout (Vertical layout) + Text (labels) + Input Field. This part works fine.

But, when keyboard is opened, the selected field is under keyboard. Is there a way to programmatically scroll the form to bring the selected field into view?

I have tried using ScrollRect.verticalNormalizedPosition and it works fine to scroll some, however I am not able to make selected field appear where I want.

Thanks for your help !


Solution

  • I am going to give you a code snippet of mine because I feel like being helpful. Hope this helps!

    protected ScrollRect scrollRect;
    protected RectTransform contentPanel;
    
    public void SnapTo(RectTransform target)
    {
        Canvas.ForceUpdateCanvases();
    
        contentPanel.anchoredPosition =
                (Vector2)scrollRect.transform.InverseTransformPoint(contentPanel.position)
                - (Vector2)scrollRect.transform.InverseTransformPoint(target.position);
    }