Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- using System;
- /// <summary>
- /// IBeginDragHandler开始拖动接口,IEndDragHandler结束拖动按钮
- /// </summary>
- public class ScrollDemo : MonoBehaviour,IBeginDragHandler,IEndDragHandler {
- [SerializeField]
- List<Toggle> toggles;
- public ScrollRect scrollRect;
- //目标位置
- public float targetPos=0;
- //public InputField inputField;
- //每页滚动区域定位
- public float[] posArr = new float[] { 0, 0.333f, 0.666f, 1f };
- //是否在被拖动
- public bool isDrag = false;
- public int curPageIndex = 0;
- // Use this for initialization
- void Start () {
- scrollRect = this.GetComponent<ScrollRect>();
- //获取所有子对象中的所有Toggle组件
- toggles = new List<Toggle>();
- this.GetComponentsInChildren<Toggle>(toggles);
- //给每一个toggle添加点击事件
- foreach (Toggle item in toggles)
- {
- item.onValueChanged.AddListener(
- delegate (bool flag)
- {
- ToggleClicked(item, flag);
- }
- );
- }
- scrollRect.horizontalNormalizedPosition = 0;
- }
- /// <summary>
- /// 单选按钮被点击时触发监听
- /// </summary>
- /// <param name="toggle">被点击按钮</param>
- /// <param name="flag">是否被点击</param>
- void ToggleClicked(Toggle toggle,bool flag)
- {
- if (flag)
- {
- //把名称中的p字符替换成空,只留下数字,然后转成int类型,做下表
- int index = int.Parse(toggle.name.Replace("p",""));
- curPageIndex = index;
- targetPos = posArr[index];
- //更新滚动区域
- //scrollRect.horizontalNormalizedPosition = posArr[index];
- }
- }
- // Update is called once per frame
- void Update () {
- //判断是否在拖动过程
- if (!isDrag)
- {
- scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition, targetPos, Time.deltaTime * 5);
- }
- }
- //开始拖动函数
- public void OnBeginDrag(PointerEventData eventData)
- {
- isDrag = true;
- }
- //结束拖动函数
- public void OnEndDrag(PointerEventData eventData)
- {
- isDrag = false;
- ////当前位置
- //float curPos = scrollRect.horizontalNormalizedPosition;
- ////误差
- //float minOffset = 0.5f;
- ////当前最近项索引
- //int posIndex = 0;
- ////通过比较,得到最近页的位置
- //for (int i = 0; i < posArr.Length;i++)
- //{
- // //记录临时差
- // float tmp=Mathf.Abs(curPos - posArr[i]);
- // if (tmp<minOffset)
- // {
- // minOffset = tmp;
- // //存储下当前索引
- // posIndex = i;
- // }
- //}
- ////更新目标位置
- //targetPos = posArr[posIndex];
- //toggles[posIndex].isOn = true;
- /********
- * 第二中方法
- **************/
- float curPos = scrollRect.horizontalNormalizedPosition;
- //根据当前和原来位置差,是正还是负,判断向左向右滑
- if (Mathf.Abs(curPos - targetPos) < 0.07f) return;
- if (curPos - targetPos > 0)
- {
- //如果向右滑,将页码+1
- curPageIndex = curPageIndex + 1 >= posArr.Length - 1 ? posArr.Length - 1 : curPageIndex + 1;
- }
- else
- {
- //向左滑,页码-1
- curPageIndex = curPageIndex - 1 <= 0 ? 0 : curPageIndex - 1;
- }
- targetPos = posArr[curPageIndex];
- toggles[curPageIndex].isOn = true;
- }
- }
Add Comment
Please, Sign In to add comment