您的位置:首页 > 移动开发 > Unity3D

Unity3D ScrollRect+ContentSizeFitter+GridLayoutGroup实现无限滚动(一)

2018-02-04 20:45 1006 查看
在工作中有时候我们会遇到无限滚动,比如相册,广告, 排行榜, 邮件等,今天就用ScrollRect来实现无限滚动,

按照滚动区域的属性,展示给玩家看的只是一小块区域,比如列表中有100封邮件,其实只要显示个七八封就够了,剩下的,在向上滑动的时候,把第一排移动到最后一排,替换内容

这样做能提高绘制效率,但是因为是在滑动的时候动画创建,所以会稍有卡顿,所以只适用于超长列表的情况使用,至于到底多长需要自己取舍。

声明:本篇的代码部分摘自于http://blog.csdn.net/huutu 转载请带上 http://www.liveslives.com/ 先看一下实现的效果图:





技术点介绍(这里我只以往上拖向下扩展进行介绍):

(一):首先UI界面布置

要注意ScrollRect的Pivot的位置要置于最上方不然运行时拉动的时候就会暴露,试一下就知道了



设置格子的布局




(二):
技术点解析:

//主要是通过获得Panel_Scroll的锚点PosY的值,这是不变的,Panel_Scroll的高即是屏幕的高1080
//获得Panel_Scroll的RectTransform PosY=1080
float scrollRectUp = scrollRect.transform.TransformPoint(Vector3.zero).y;
//纵向滑动改变的只是格子锚点的PosY
Vector3 childBottomLeft = new Vector3(children[0].anchoredPosition.x, children[0].anchoredPosition.y - gridLayoutGroup.cellSize.y, 0f);
//将格子的局部坐标转为世界坐标再与1080比较,移动格子,当格子的走过的高当大于等于1080时,那么重新设置该格子的层级SetAsLastSibling(即从index=0的位置移动到index=5的位置.)
float childBottom = transform.TransformPoint(childBottomLeft).y;
(三): 向上拉向下扩展的代码:

if (offsetY > 0)
{
//向上拉,向下扩展;
{
if (realIndex >= amount - 1)
{
startPosition = currentPos;
return;
}

float scrollRectUp = scrollRect.transform.TransformPoint(Vector3.zero).y;
Vector3 childBottomLeft = new Vector3(children[0].anchoredPosition.x, children[0].anchoredPosition.y - gridLayoutGroup.cellSize.y, 0f);
float childBottom = transform.TransformPoint(childBottomLeft).y;
if (childBottom >= scrollRectUp)
{
//Debug.Log("childBottom >= scrollRectUp");

//移动到底部;
for (int index = 0; index < gridLayoutGroup.constraintCount; index++)
{
children[index].SetAsLastSibling();
children[index].anchoredPosition = new Vector2(children[index].anchoredPosition.x, children[children.Count - 1].anchoredPosition.y - gridLayoutGroup.cellSize.y - gridLayoutGroup.spacing.y);
Debug.Log("这是格子的PosX" + children[index].anchoredPosition.x);
Debug.Log("这是格子的PosY" + children[children.Count - 1]);
Debug.Log("第几个啦" + gridLayoutGroup.constraintCount);
realIndex++;

if (realIndex > amount - 1)
{
children[index].gameObject.SetActive(false);
}
else
{
UpdateChildrenCallback(realIndex, children[index]);
}
}

//GridLayoutGroup 底部加长;
rectTransform.sizeDelta += new Vector2(0, gridLayoutGroup.cellSize.y + gridLayoutGroup.spacing.y);

//更新child;
for (int index = 0; index < children.Count; index++)
{
children[index] = transform.GetChild(index).GetComponent<RectTransform>();
}
}
}
}

下一篇给大家分享一个无限滚动排行榜的Demo

以上是对原博主的案例调试解析,如有疑问欢迎交流我的邮箱2285557632@qq.com

工程案例下载:

https://github.com/WMengTing/InfiniteScrolling
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: