31

我使用 Unity 5.1 为手机游戏构建了一个注册表单。为此,我使用Unity UI组件:ScrollRect + Autolayout(垂直布局)+ Text(标签)+ Input Field。这部分工作正常。

但是,当键盘打开时,所选字段在键盘下方。有没有办法以编程方式滚动表单以显示所选字段?

我已经尝试使用ScrollRect.verticalNormalizedPosition并且滚动一些效果很好,但是我无法使选定的字段出现在我想要的位置。

谢谢你的帮助 !

4

12 回答 12

67

我将给你一个我的代码片段,因为我觉得很有帮助。希望这可以帮助!

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);
}
于 2015-06-11T00:20:56.343 回答
19

没有任何建议对我有用,以下代码确实

这是扩展名

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

这就是我如何使用它来将内容的直接子项滚动到视图中

    private void Update()
    {
        MyScrollRect.content.localPosition = MyScrollRect.GetSnapToPositionToBringChildIntoView(someChild);
    }
于 2018-05-05T16:48:06.480 回答
8

尽管@maksymiuk 的答案是最正确的答案,因为由于 InverseTransformPoint() 函数,它正确地考虑了锚点、枢轴和所有其他因素,但它对我来说仍然无法开箱即用 - 对于垂直滚动器,它是也改变它的 X 位置。所以我只是进行了更改以检查是否启用了垂直或水平滚动,如果没有则不更改它们的轴。

public static void SnapTo( this ScrollRect scroller, RectTransform child )
{
    Canvas.ForceUpdateCanvases();

    var contentPos = (Vector2)scroller.transform.InverseTransformPoint( scroller.content.position );
    var childPos = (Vector2)scroller.transform.InverseTransformPoint( child.position );
    var endPos = contentPos - childPos;
    // If no horizontal scroll, then don't change contentPos.x
    if( !scroller.horizontal ) endPos.x = contentPos.x;
    // If no vertical scroll, then don't change contentPos.y
    if( !scroller.vertical ) endPos.y = contentPos.y;
    scroller.content.anchoredPosition = endPos;
}
于 2020-02-06T21:12:28.130 回答
7

这是我将选定对象夹入 ScrollRect 的方式

private ScrollRect scrollRect;
private RectTransform contentPanel;

public void ScrollReposition(RectTransform obj)
{
    var objPosition = (Vector2)scrollRect.transform.InverseTransformPoint(obj.position);
    var scrollHeight = scrollRect.GetComponent<RectTransform>().rect.height;
    var objHeight = obj.rect.height;

    if (objPosition.y > scrollHeight / 2)
    {
        contentPanel.localPosition = new Vector2(contentPanel.localPosition.x,
            contentPanel.localPosition.y - objHeight - Padding.top);
    }

    if (objPosition.y < -scrollHeight / 2)
    {
        contentPanel.localPosition = new Vector2(contentPanel.localPosition.x,
contentPanel.localPosition.y + objHeight + Padding.bottom);
    }
}
于 2016-05-17T15:43:35.883 回答
3

我这个问题的版本的前提条件:

  • element我想滚动到的应该是完全可见的(间隙最小)
  • 是的内容element的直接子级scrollRect
  • element如果已经完全可见,则保持 scoll 位置
  • 我只关心垂直尺寸

这对我来说最有效(感谢其他灵感):

// ScrollRect scrollRect;
// RectTransform element;
// Fully show `element` inside `scrollRect` with at least 25px clearance
scrollArea.EnsureVisibility(element, 25);

使用此扩展方法:

public static void EnsureVisibility(this ScrollRect scrollRect, RectTransform child, float padding=0)
{
    Debug.Assert(child.parent == scrollRect.content,
        "EnsureVisibility assumes that 'child' is directly nested in the content of 'scrollRect'");

    float viewportHeight = scrollRect.viewport.rect.height;
    Vector2 scrollPosition = scrollRect.content.anchoredPosition;

    float elementTop = child.anchoredPosition.y;
    float elementBottom = elementTop - child.rect.height;

    float visibleContentTop = -scrollPosition.y - padding;
    float visibleContentBottom = -scrollPosition.y - viewportHeight + padding;

    float scrollDelta =
        elementTop > visibleContentTop ? visibleContentTop - elementTop :
        elementBottom < visibleContentBottom ? visibleContentBottom - elementBottom :
        0f;

    scrollPosition.y += scrollDelta;
    scrollRect.content.anchoredPosition = scrollPosition;
}
于 2020-05-06T09:56:02.487 回答
2

如果有人在寻找平滑滚动(使用 lerp)。

[SerializeField]
private ScrollRect _scrollRectComponent; //your scroll rect component
[SerializeField]
RectTransform _container; //content transform of the scrollrect
private IEnumerator LerpToChild(RectTransform target)
{
    Vector2 _lerpTo = (Vector2)_scrollRectComponent.transform.InverseTransformPoint(_container.position) - (Vector2)_scrollRectComponent.transform.InverseTransformPoint(target.position);
    bool _lerp = true;
    Canvas.ForceUpdateCanvases();

    while(_lerp)
    {
        float decelerate = Mathf.Min(10f * Time.deltaTime, 1f);
        _container.anchoredPosition = Vector2.Lerp(_scrollRectComponent.transform.InverseTransformPoint(_container.position), _lerpTo, decelerate);
        if (Vector2.SqrMagnitude((Vector2)_scrollRectComponent.transform.InverseTransformPoint(_container.position) - _lerpTo) < 0.25f)
        {
            _container.anchoredPosition = _lerpTo;
            _lerp = false;
        }
        yield return null;
    }
}
于 2020-06-30T11:59:20.180 回答
2

Peter Morris 的一个变体回答 ScrollRects 具有“弹性”的运动类型。令我困扰的是,滚动矩形一直在为边缘情况(第一个或最后几个元素)设置动画。希望它有用:

/// <summary>
/// Thanks to https://stackoverflow.com/a/50191835
/// </summary>
/// <param name="instance"></param>
/// <param name="child"></param>
/// <returns></returns>
public static IEnumerator BringChildIntoView(this UnityEngine.UI.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)
    );
    instance.content.localPosition = result;

    yield return new WaitForUpdate();

    instance.horizontalNormalizedPosition = Mathf.Clamp(instance.horizontalNormalizedPosition, 0f, 1f);
    instance.verticalNormalizedPosition = Mathf.Clamp(instance.verticalNormalizedPosition, 0f, 1f);
}

它虽然引入了一帧延迟。

更新:这是一个不引入帧延迟的版本,它还考虑了内容的缩放:

/// <summary>
/// Based on https://stackoverflow.com/a/50191835
/// </summary>
/// <param name="instance"></param>
/// <param name="child"></param>
/// <returns></returns>
public static void BringChildIntoView(this UnityEngine.UI.ScrollRect instance, RectTransform child)
{
    instance.content.ForceUpdateRectTransforms();
    instance.viewport.ForceUpdateRectTransforms();

    // now takes scaling into account
    Vector2 viewportLocalPosition = instance.viewport.localPosition;
    Vector2 childLocalPosition = child.localPosition;
    Vector2 newContentPosition = new Vector2(
        0 - ((viewportLocalPosition.x * instance.viewport.localScale.x) + (childLocalPosition.x * instance.content.localScale.x)),
        0 - ((viewportLocalPosition.y * instance.viewport.localScale.y) + (childLocalPosition.y * instance.content.localScale.y))
    );

    // clamp positions
    instance.content.localPosition = newContentPosition;
    Rect contentRectInViewport = TransformRectFromTo(instance.content.transform, instance.viewport);
    float deltaXMin = contentRectInViewport.xMin - instance.viewport.rect.xMin;
    if(deltaXMin > 0) // clamp to <= 0
    {
        newContentPosition.x -= deltaXMin;
    }
    float deltaXMax = contentRectInViewport.xMax - instance.viewport.rect.xMax;
    if (deltaXMax < 0) // clamp to >= 0
    {
        newContentPosition.x -= deltaXMax;
    }
    float deltaYMin = contentRectInViewport.yMin - instance.viewport.rect.yMin;
    if (deltaYMin > 0) // clamp to <= 0
    {
        newContentPosition.y -= deltaYMin;
    }
    float deltaYMax = contentRectInViewport.yMax - instance.viewport.rect.yMax;
    if (deltaYMax < 0) // clamp to >= 0
    {
        newContentPosition.y -= deltaYMax;
    }

    // apply final position
    instance.content.localPosition = newContentPosition;
    instance.content.ForceUpdateRectTransforms();
}

/// <summary>
/// Converts a Rect from one RectTransfrom to another RectTransfrom.
/// Hint: use the root Canvas Transform as "to" to get the reference pixel positions.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
public static Rect TransformRectFromTo(Transform from, Transform to)
{
    RectTransform fromRectTrans = from.GetComponent<RectTransform>();
    RectTransform toRectTrans = to.GetComponent<RectTransform>();

    if (fromRectTrans != null && toRectTrans != null)
    {
        Vector3[] fromWorldCorners = new Vector3[4];
        Vector3[] toLocalCorners = new Vector3[4];
        Matrix4x4 toLocal = to.worldToLocalMatrix;
        fromRectTrans.GetWorldCorners(fromWorldCorners);
        for (int i = 0; i < 4; i++)
        {
            toLocalCorners[i] = toLocal.MultiplyPoint3x4(fromWorldCorners[i]);
        }

        return new Rect(toLocalCorners[0].x, toLocalCorners[0].y, toLocalCorners[2].x - toLocalCorners[1].x, toLocalCorners[1].y - toLocalCorners[0].y);
    }

    return default(Rect);
}
于 2020-05-25T15:23:06.703 回答
1

是的,这可以使用编码垂直滚动,请尝试以下代码:

//Set Scrollbar Value - For Displaying last message of content
Canvas.ForceUpdateCanvases ();
verticleScrollbar.value = 0f;
Canvas.ForceUpdateCanvases ();

当我开发聊天功能时,这段代码对我来说很好。

于 2016-05-16T11:17:53.210 回答
0

垂直调整:

[SerializeField]
private ScrollRect _scrollRect;

private void ScrollToCurrentElement()
{
    var siblingIndex = _currentListItem.transform.GetSiblingIndex();

    float pos = 1f - (float)siblingIndex / _scrollRect.content.transform.childCount;

    if (pos < 0.4)
    {
        float correction = 1f / _scrollRect.content.transform.childCount;
        pos -= correction;
    }

    _scrollRect.verticalNormalizedPosition = pos;
} 
于 2020-02-14T13:58:38.127 回答
0

简单且完美运行

            var pos = 1 - ((content.rect.height / 2 - target.localPosition.y) / content.rect.height);
            scrollRect.normalizedPosition = new Vector2(0, pos);
于 2021-12-23T11:18:38.377 回答
0

这是我为解决这个问题而创建的。将此行为放在可以通过控制器 UI 导航选择的每个按钮上。它支持完全嵌套的子对象。它只支持垂直滚动,但可以很容易地适应水平滚动。

    using UnityEngine;
    using System;
    using UnityEngine.EventSystems;
    using UnityEngine.UI;
    
    namespace Legend
    {
        public class ScrollToOnSelect: MonoBehaviour, ISelectHandler
        {
            ScrollRect scrollRect;
            RectTransform target;
    
            void Start()
            {
                scrollRect = GetComponentInParent<ScrollRect>();
                target = (RectTransform)this.transform;
            }
    
            Vector3 LocalPositionWithinAncestor(Transform ancestor, Transform target)
            {
                var result = Vector3.zero;
                while (ancestor != target && target != null)
                {
                    result += target.localPosition;
                    target = target.parent;
                }
                return result;
            }
    
            public void EnsureScrollVisible()
            {
                Canvas.ForceUpdateCanvases();
    
                var targetPosition = LocalPositionWithinAncestor(scrollRect.content, target);
                var top = (-targetPosition.y) - target.rect.height / 2;
                var bottom = (-targetPosition.y) + target.rect.height / 2;
    
                var topMargin = 100; // this is here because there are headers over the buttons sometimes
    
                var result = scrollRect.content.anchoredPosition;
                if (result.y > top - topMargin)
                    result.y = top - topMargin;
                if (result.y + scrollRect.viewport.rect.height < bottom)
                    result.y = bottom - scrollRect.viewport.rect.height;
    
                //Debug.Log($"{targetPosition} {target.rect.size} {top} {bottom} {scrollRect.content.anchoredPosition}->{result}");
    
                scrollRect.content.anchoredPosition = result;
            }
    
            public void OnSelect(BaseEventData eventData)
            {
                if (scrollRect != null)
                    EnsureScrollVisible();
            }
        }
    }
于 2021-09-25T16:47:52.793 回答
0

width 表示滚动矩形中子元素的宽度(假设所有子元素宽度相同),间距表示子元素之间的间距,索引表示您要到达的目标元素

public float getSpecificItem (float pWidth, float pSpacing,int pIndex) {
    return (pIndex * pWidth) - pWidth + ((pIndex - 1) * pSpacing);
}
于 2019-11-22T08:26:29.497 回答