NGUI ScrollView 回弹控制

最近在处理项目时,遇到一个棘手的问题,搞了好久终于把他弄出来了。项目要求实现一个功能,就是当在ScrollView滚动到终点的时候,控制ScrollView回弹到初始的位置,比如列表有14条数据,当滑动到第14条数据的时候,需要自动返回到第一条数据的位置。

在功能实现的时候,主要使用了ScrollView的监听事件,配合ScrollView移动控制的类SpringPanel完成的。

首先我们了解一下ScrollView的事件。
1 onDragStarted 开始拖动,鼠标点击ScrollView的时候开始调用
2 onMomentumMove 正在滑动,拖动ScrollView的时候调用
3 onDragFinished停止拖动,松开鼠标或手指。停止拖动ScrollView的时候调用
4 onStoppedMoving 在拖同结束,系统移动ScrollView结束的时候调用

然后,我们了解一下SpringPanel的Begin方法,

static public SpringPanel Begin (GameObject go, Vector3 pos, float strength)

go表示要弹回的gameObject对象,这里指的是ScrollView
pos:你要弹回的位置,这里保存的是ScrollView的起始位置,这里用的是局部坐标位置
strength:弹回力度,strength越大,移动越快。

代码

using UnityEngine;
using System.Collections;

public class CardList : MonoBehaviour
{
    UIScrollView sc;
    Vector3 constraint = Vector3.zero; //scrollView 的偏移量
    Vector3 offset = Vector3.zero;//scrollView 的最大偏移量
    float length;
    Vector3 startPos;
    Vector2 size;
    // Use this for initialization
    void Start()
    {
        sc = this.GetComponent<UIScrollView>();
        //scrollView 的事件绑定
        sc.onDragFinished += DragFinished;
        sc.onStoppedMoving += StoppedMoving;
        sc.onMomentumMove += MomentumMove;

         length = sc.GetComponentInChildren<UIGrid>().cellWidth * 7;//scrowView的最大长度
        Debug.Log("length:" + length);
        startPos = sc.gameObject.transform.localPosition;//起始位置
        size = sc.panel.GetViewSize();//scroview显示的宽度
        //Debug.Log("size:" + size);
    }

    private void StoppedMoving()
    {
        Debug.Log("StopMove");

        float currentLength = offset.x + size.x;
        //Debug.Log("currentLength" + currentLength);
        if(currentLength>=length){
            offset = Vector3.zero;
            SpringPanel.Begin(sc.gameObject, startPos, 3);
        }

    }

    private void MomentumMove()
    {
        //计算x轴的偏移量
        constraint = sc.panel.CalculateConstrainOffset(sc.bounds.min, sc.bounds.min);
        if (constraint.x > offset.x)
        {
            offset = constraint;//保存x轴的最大偏移量
        }

    }

    private void DragFinished()
    {
        Debug.Log("DragFinished");

    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯过客TYGK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值