Ugui滑动翻页_滑动翻页

using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class PageView : MonoBehaviour, IBeginDragHandler, IEndDragHandler
{
#region 数据申明

private ScrollRect scrollRect;
public int totalObjectCount { get; private set; }
public int totalPageNumber { get; private set; }
public int onePageObjectCount = 1;
public float smooting = 4;
private float targethorizontal = 0;
private bool isDrag = false;
private float spacing;
public int currentPage { get; private set; }
private float beginPs;
private float endPs;

public event Action<int> onChagePage = null;

#endregion

#region Unity函数

private void Awake()
{
scrollRect = transform.GetComponent<ScrollRect>();

int count = 0;
foreach (Transform tf in scrollRect.content) { if (tf.gameObject.activeInHierarchy) count++; }
SetItemCount(count);
}

private void OnEnable()
{
scrollRect.horizontalNormalizedPosition = 0;
}

private void Update()
{
if (isDrag) return;
scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition, targethorizontal, Time.deltaTime * smooting);
}

#endregion

#region 公开函数

/// <summary>手动设置Item数量</summary>
public void SetItemCount(int Count)
{
totalObjectCount = Count;
totalPageNumber = (totalObjectCount / onePageObjectCount);
if ((totalObjectCount % onePageObjectCount) != 0) totalPageNumber++;
spacing = 1f / (totalObjectCount - onePageObjectCount);
}

/// <summary>设置页码</summary>
public void SetPage(int page)
{
int temp = Mathf.Clamp(page - 1, 0, totalPageNumber - 1);
targethorizontal = (spacing * onePageObjectCount) * temp;
currentPage = page;
if (onChagePage != null) onChagePage(page);
}

/// <summary>拖动开始</summary>
public void OnBeginDrag(PointerEventData eventData)
{
isDrag = true;
beginPs = Input.mousePosition.x;
}

/// <summary>拖拽结束</summary>
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;

int page = currentPage;

endPs = Input.mousePosition.x;
float offset = Math.Abs(endPs - beginPs);

if(offset>30)
{
if (endPs < beginPs) page++;
else page--;

page = Mathf.Clamp((int)page, 1, totalPageNumber);
SetPage(page);
}
}

#endregion

}

 

欢迎对AR技术感兴趣的朋友,加入QQ群:883655607 讨论