UGUI ScrollRect实现带按钮翻页支持拖拽
程序员文章站
2022-09-02 08:58:13
本文实例为大家分享了ugui scrollrect带按钮翻页支持拖拽的具体代码,供大家参考,具体内容如下using unityengine;using system.collections;using...
本文实例为大家分享了ugui scrollrect带按钮翻页支持拖拽的具体代码,供大家参考,具体内容如下
using unityengine; using system.collections; using unityengine.ui; using unityengine.eventsystems; using system.collections.generic; using system; /// <summary> /// 略知csharp /// </summary> public class scrollrecthelper : monobehaviour, ibegindraghandler, ienddraghandler { public float smooting = 5; //滑动速度 public list<gameobject> listitem; //scrollview item public int pagecount = 3; //每页显示的项目 scrollrect srect; float pageindex; //总页数 bool isdrag = false; //是否拖拽结束 list<float> listpagevalue = new list<float> { 0 }; //总页数索引比列 0-1 float targetpos = 0; //滑动的目标位置 float nowindex = 0; //当前位置索引 void awake() { srect = getcomponent<scrollrect>(); listpagevalueinit(); } //每页比例 void listpagevalueinit() { pageindex = (listitem.count / pagecount)-1; if (listitem != null && listitem.count != 0) { for (float i = 1; i <= pageindex; i++) { listpagevalue.add((i / pageindex)); } } } void update() { if (!isdrag) srect.horizontalnormalizedposition = mathf.lerp(srect.horizontalnormalizedposition, targetpos, time.deltatime * smooting); } /// <summary> /// 拖动开始 /// </summary> /// <param name="eventdata"></param> public void onbegindrag(pointereventdata eventdata) { isdrag = true; } /// <summary> /// 拖拽结束 /// </summary> /// <param name="eventdata"></param> public void onenddrag(pointereventdata eventdata) { isdrag = false; var temppos = srect.horizontalnormalizedposition; //获取拖动的值 var index = 0; float offset = mathf.abs(listpagevalue[index] - temppos); //拖动的绝对值 for (int i = 1; i < listpagevalue.count; i++) { float temp = mathf.abs(temppos - listpagevalue[i]); if (temp < offset) { index = i; offset = temp; } } targetpos = listpagevalue[index]; nowindex = index; } public void btnleftgo() { nowindex = mathf.clamp(nowindex - 1, 0, pageindex); targetpos = listpagevalue[convert.toint32(nowindex)]; } public void btnrightgo() { nowindex = mathf.clamp(nowindex + 1, 0, pageindex); targetpos = listpagevalue[convert.toint32(nowindex)]; } }
demo 下载地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。