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 !
To begin, we need to add the Scroll Rect (Script) component to the panel. Keeping the panel selected, drag the image that is parented to the panel into the Content variable inside Scroll Rect (Script). By default, the image is set to have an elastic effect, which, in most cases, is quite nice.
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); }
None of the suggestions worked for me, the following code did
Here is the extension
using UnityEngine; using UnityEngine.UI; namespace BlinkTalk { public static class ScrollRectExtensions { public static Vector2 GetSnapToPositionToBringChildIntoView(this ScrollRect instance, RectTransform child) { Canvas.ForceUpdateCanvases(); Vector2 viewportLocalPosition = instance.viewport.localPosition; Vector2 childLocalPosition = child.localPosition; Vector2 result = new Vector2( 0 - (viewportLocalPosition.x + childLocalPosition.x), 0 - (viewportLocalPosition.y + childLocalPosition.y) ); return result; } } }
And here is how I used it to scroll a direct child of the content into view
private void Update() { MyScrollRect.content.localPosition = MyScrollRect.GetSnapToPositionToBringChildIntoView(someChild); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With