直接上代码:
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.001f)
{
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];
// 左右拖拽灵敏顺滑
//isDrag = false;
//endDragPos = sRect.horizontalNormalizedPosition; //获取拖动的值
//if (endDragPos < m_targetPos)
//{
// index--;
// if (index < 0)
// {
// index = 0;
// }
// m_targetPos = listPageValue[index];
//}
//else
//{
// index++;
// if (index > pageCount - 1)
// {
// index = pageCount - 1;
// }
// 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);
}
}
}
提示:
将这个脚本挂在scrollView
控件上,设置scrollView里面content的right
和scrollView的width
pageCount
根据right
和width
算出
参考:https://blog.csdn.net/qq302756113/article/details/81132591
网友评论