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

Florent Morin picture Florent Morin · Jun 10, 2015 · Viewed 47.3k times · Source

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 !

Answer

maksymiuk picture maksymiuk · Jun 11, 2015

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