Unity使用ScrollRect制作翻页
本文实例为大家分享了使用ScrollRect制作翻页的具体代码,供大家参考,具体内容如下
1.标准的层级结构ScrollRect->ViewPort->Content,Viewport负责显示区域的大小一般和Mask一起配合使用,Content使用Layout来布局,如果想使用代码来自动定位显示位置需要在Content加上Contentsizefilter.
2.ScrollRectHelper
usingUnityEngine;
usingUnityEngine.UI;
usingUnityEngine.EventSystems;
usingSystem.Collections.Generic;
usingSystem;
publicclassScrollRectHelper:MonoBehaviour,IBeginDragHandler,IEndDragHandler
{
//滑动速度
publicfloatsmooting=5;
//每页显示的项目
[SerializeField]
privateintcountPerPage=10;
ScrollRectsrect;
//总页数
floattotalPages;
//是否拖拽结束
boolisDrag=false;
//总页数索引比列0-1
ListlistPageValue=newList{0};
//滑动的目标位置
publicfloattargetPos=0;
//当前位置索引
floatnowindex=0;
voidAwake()
{
srect=GetComponent();
}
publicstringPageText()
{
return(nowindex+1)+"/"+(totalPages+1);
}
//计算每页比例
publicvoidCalcListPageValue()whereT:MonoBehaviour
{
T[]items=srect.content.GetComponentsInChildren();
srect.content.rect.Set(srect.content.rect.width/2,srect.content.rect.y,srect.content.rect.width,srect.content.rect.height);
totalPages=(int)(Math.Ceiling((float)items.Length/countPerPage)-1);
if(items.Length!=0)
{
for(floati=1;i<=totalPages;i++)
{
//Debug.Log(i/totalPages);
listPageValue.Add((i/totalPages));
}
}
}
voidUpdate()
{
if(!isDrag)
{
srect.horizontalNormalizedPosition=Mathf.Lerp(srect.horizontalNormalizedPosition,targetPos,
Time.deltaTime*smooting);
}
//Debug
if(Input.GetKeyDown(KeyCode.LeftArrow))PressLeft();
if(Input.GetKeyDown(KeyCode.RightArrow))PressRight();
}
///
///拖动开始
///
///
publicvoidOnBeginDrag(PointerEventDataeventData)
{
isDrag=true;
}
///
///拖拽结束
///
///
publicvoidOnEndDrag(PointerEventDataeventData)
{
isDrag=false;
vartempPos=srect.horizontalNormalizedPosition;//获取拖动的值
varindex=0;
floatoffset=Mathf.Abs(listPageValue[index]-tempPos);//拖动的绝对值
for(inti=1;i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。