最近在处理项目时,遇到一个棘手的问题,搞了好久终于把他弄出来了。项目要求实现一个功能,就是当在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");
}
}