using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// UGUI无限滚动列表
///(by:羽落星辰)
/// </summary>
public class UGUILoopScrollView : MonoBehaviour
{
//方向
public enum Direction
{
Horizontal, //水平
Vertical, //垂直
}
//暂时默认是1
[Header("每行/列Cell数量")]
[SerializeField]
private int cellConstraintCount = 1;
[Header("Cell尺寸")]
[SerializeField]
private Vector2 CellSize;
[Header("Cell之间的间距")]
[SerializeField]
private Vector2 Spacing;
[Header("Cell起始位置空余")]
[SerializeField]
private float Padding;
[Header("排列方向")]
[SerializeField]
private Direction direction = Direction.Horizontal;
[Header("Cell物体(必须赋值)")]
public GameObject mCellObj;
[Header("滑动框组件(默认是当前物体的父级,其他情况请赋值)")]
public ScrollRect mScrollView;
#region CacheData
//Content组件
private RectTransform uiTransform;
//ScrollRect组件
private RectTransform scrollTransform;
//Cell列表
private List<GameObject> list_Cell;
//list类型的数据结构
private IList cellDatas;
//Cell生成的个数
private int cellCount;
//Cell数据需要的个数
private int cellDataCount;
//当前显示的最小值(列或者行)
private int minRow;
//当前显示的最大值(列或者行)
private int maxRow;
//cell的回调事件
private Action<GameObject, int> cellCallBack;
#endregion
private void Awake()
{
uiTransform = transform.GetComponent<RectTransform>();
if (transform.parent.GetComponent<ScrollRect>())
mScrollView = transform.parent.GetComponent<ScrollRect>();
if (!mScrollView)
{
Debug.LogError("ScrollView is null , pleace check it...");
return;
}
scrollTransform = mScrollView.GetComponent<RectTransform>();
//设置滑动框 滑动方向
SetScrollRectDirection();
if (mScrollView)
{
mScrollView.onValueChanged.AddListener((value) =>
{
RefreshCellPosition();
});
}
}
/// <summary>
/// 创建Cell
/// </summary>
public void CreateCell()
{
//ScrollView的高度(垂直模式)或者宽度(水平模式)
float scrollViewValue;
//cell的高度(垂直模式)或者宽度(水平模式)
float cellValue;
scrollViewValue = (direction == Direction.Horizontal) ? scrollTransform.sizeDelta.x : scrollTransform.sizeDelta.y;
cellValue = (direction == Direction.Horizontal) ? CellSize.x : CellSize.y;
int createCellCount = (Mathf.CeilToInt(scrollViewValue / cellValue) * cellConstraintCount) + 3 * cellConstraintCount;
list_Cell = new List<GameObject>(createCellCount);
GameObject cellTemp;
Vector3 cellPos = Vector3.zero;
for (int i = 0; i < createCellCount; i +=