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 討論