直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class ScrollViewControl : MonoBehaviour, IBeginDragHandler, IEndDragHandler { public GameObject button_left; // 左翻页 public GameObject button_right; // 右翻页 public int pageCount = 0; // 总页数 private ScrollRect sRect; // 滚动组件 private float endDragPos; // 拖拽结束位置0-1 private bool isDrag = false; // 是否拖拽结束 private float m_targetPos = 0; // 滑动的目标位置0-1 private float smooting = 5; // 滑动速度 private List<float> listPageValue = new List<float> { }; // 总页数索引比列 0-1 private int index = 0; // listPageValue下标 void Start() { sRect = this.GetComponent<ScrollRect>(); // 初始化listPageValue数组 ListPageValueInit(); } void Update() { // 开始拖拽或移动结束直接返回 if (isDrag == true) { return; } // 移动结束 if (!isDrag && System.Math.Abs(sRect.horizontalNormalizedPosition - m_targetPos) < 0.0001f) { MovedEnd(); isDrag = true; return; } // 以当前位置按指定速度朝目标位置移动 sRect.horizontalNormalizedPosition = Mathf.Lerp(sRect.horizontalNormalizedPosition, m_targetPos, Time.deltaTime * smooting); } // 每页比例 void ListPageValueInit() { for (float i = 0; i < pageCount; i++) { listPageValue.Add(i / (pageCount - 1)); } } // 拖动开始 public void OnBeginDrag(PointerEventData eventData) { isDrag = true; // 隐藏左右翻页按钮 button_left.SetActive(false); button_right.SetActive(false); } // 拖拽结束 public void OnEndDrag(PointerEventData eventData) { isDrag = false; endDragPos = sRect.horizontalNormalizedPosition; // 获取拖动的值 index = 0; float offset = Mathf.Abs(listPageValue[index] - endDragPos); // 拖动的绝对值 for (int i = 1; i < listPageValue.Count; i++) { float temp = Mathf.Abs(endDragPos - listPageValue[i]); if (temp < offset) { index = i; offset = temp; } } // 目标位置 m_targetPos = listPageValue[index]; } // 移动结束 void MovedEnd() { // 如果就一页直接返回 if (pageCount <= 1) { return; } // 显示/隐藏左右翻页按钮 if (index == 0) { button_left.SetActive(false); button_right.SetActive(true); } else if (index == pageCount - 1) { button_left.SetActive(true); button_right.SetActive(false); } else { button_left.SetActive(true); button_right.SetActive(true); } } } |
提示:
参考:https://blog.csdn.net/qq302756113/article/details/81132591