栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

UGUI ScrollRect实现带按钮翻页支持拖拽

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

UGUI ScrollRect实现带按钮翻页支持拖拽

本文实例为大家分享了UGUI ScrollRect带按钮翻页支持拖拽的具体代码,供大家参考,具体内容如下

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using System;
/// 
/// 略知CSharp 
/// 
public class ScrollRectHelper : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
 
 public float smooting = 5;    //滑动速度
 public List listItem;   //scrollview item 
 public int pageCount = 3;    //每页显示的项目
 
 ScrollRect srect;
 float pageIndex;     //总页数
 bool isDrag = false;    //是否拖拽结束
 List listPagevalue = new List { 0 }; //总页数索引比列 0-1
 float targetPos = 0;    //滑动的目标位置
 float nowindex = 0;     //当前位置索引
 
 void Awake()
 {
 srect = GetComponent();
 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);
 }
 /// 
 /// 拖动开始
 /// 
 /// 
 public void onBeginDrag(PointerEventData eventData)
 {
 isDrag = true;
 }
 /// 
 /// 拖拽结束
 /// 
 /// 
 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 下载地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/122086.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号