一个列表数据可能是几十上百条的,而在UGUI中,虽然Item移出了Content为不可见但其任然占用了资源,而我们能看到的Item数量仅仅是在界面上的五六个。
那么我们优化的方式就是重复利用这五六个Item,超出的Item补位到即将出现的Item位置。
我们需要的就是监听列表滑动,根据子物体宽高,子物体间距计算出容纳数量,以及滑动之后第一个能显示的item是第几个数据,然后再将上面超出范围的或者下面超出范围的子物体往上或者往下填充,即可实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BaseList<T> {
public delegate Transform SetElement(Transform transform, T itemData);
public int columnCount = 1; //显示列数
public float rowDistance; //行距
public float columnDistance; //列距
private int rowCount; // 可显示行数
private Transform content; //List的基本组件
private float parentWidth = 0; //List的宽度
private float parentHeight = 0; //List的高度
private Transform itemTransform; //显示的ITem
private float itemWidth = 0; //子物体宽度
private float itemHeight = 0; //子物体高度
private int showCount = 0; //显示的子物体数量
private float visualScope = 0; //可视范围
private float overallLength = 0; //总长度
private float contentStartPos = 0; //开始位置
private float maxY; //最大可显示高度
private float minY; //最小可显示高度
private Transform rootTransform = null;
//private List dataList = null;
private List<T> dataList;
private SetElement setElement;
private Stack<Transform> itemStack; //搞个栈存储Item,方便存取
private Dictionary<int, Transform> itemDictionary = new Dictionary<int, Transform>();
///
/// 第一个参数是设置的列表数据
/// 第二个参数是设置显示方式的方法
///
///
///
///
public void SetParam(List<T> list, SetElement setElement,Transform root,float rowDistance,float columnDistance)
{
this.rowDistance = rowDistance;
this.columnDistance = columnDistance;
rootTransform = root;
dataList = list;
this.setElement = setElement;
InitParameter();
SetData();
}
///
/// 参数初始化
///
private void InitParameter()
{
content = rootTransform.Find("Viewport/Content");
contentStartPos = content.localPosition.y;
visualScope = rootTransform.GetComponent<RectTransform>().rect.height;
itemTransform = rootTransform.Find("Viewport/Item").transform;
itemTransform.gameObject.SetActive(false);
Rect itemRect = itemTransform.GetComponent<RectTransform>().rect;
itemWidth = itemRect.width;
itemHeight = itemRect.height;
parentWidth = rootTransform.GetComponent<RectTransform>().rect.width;
parentHeight = rootTransform.GetComponent<RectTransform>().rect.height;
int maxcolumnCount = (int)(parentWidth / itemWidth); //最大行数
if (maxcolumnCount < (columnCount))
columnCount = maxcolumnCount;
rowCount = (int)((parentHeight - (rowDistance + itemHeight / 2)) / (rowDistance + itemHeight) + 1);
showCount = columnCount * rowCount;
maxY = itemHeight / 2;
minY = (rowDistance + itemHeight) * rowCount;
}
///
/// 设置元素
///
///
public void SetData()
{
int maxCount = dataList.Count;
int index = 0;
overallLength = (itemHeight + rowDistance) * maxCount / columnCount;
content.GetComponent<RectTransform>().sizeDelta = new Vector2(0, overallLength); //重新计算Content的宽高用来装Item,但是这个x轴的宽度很神奇填0是ok的但是不规范坐等大神解决(自行调试发现问题我暂时没有解决)
ScrollRect scrollRect = rootTransform.GetComponent<ScrollRect>();
if (scrollRect != null)
{
scrollRect.onValueChanged.AddListener(OnValueChange); //监听滑动值的改变,传入的是位置信息
}
for (int row = 0; row < rowCount + 1; row++)
{
for (int column = 0; column < columnCount; column++)
{
if (index >= maxCount)
{
return;
}
Transform itemTrans = setElement(GameObject.Instantiate(itemTransform.gameObject).transform, dataList[index]);
itemTrans.parent = content.transform;
itemTrans.gameObject.SetActive(true);
itemTrans.GetComponent<RectTransform>().anchorMin = new Vector2(0, 1);
itemTrans.GetComponent<RectTransform>().anchorMax = new Vector2(0, 1);
float x = (column * (itemWidth + columnDistance) + itemWidth / 2 + columnDistance);
//前面物体的距离=行数*(物体高度+物体间离)
//自己再往后退半个+间距
float y = -(row * (itemHeight + rowDistance) + itemHeight / 2 + rowDistance);
itemTrans.localPosition = new Vector2(x, y); //设置位置
itemDictionary.Add(index, itemTrans);
index++;
}
if (index >= maxCount)
{
return;
}
}
}
///
/// 监听List滑动
/// 记录一下思路,我们需要的是显示在可视范围内的物体
/// 这个移动监听事件的值是0-1,最上面是1,最下面是0
/// 我们现在有最大长度,可视长度,可视长度/最大长度 = 可视比例 比如长度是10,可视距离是1,我们的可视比例是1/10
/// 那么如果我们把页面拉到0.2的时候,只要子物体在0.2*最大长度和0.2*(1/10)*最大长度的范围内,我们就让它进行显示,超出这个范围的就存到栈内
///
///
public void OnValueChange(Vector2 vector)
{
int startIndex = GetShowIndex();
//不能小于第一个,不能大到剩下的item不足以容下完整一页
if (startIndex < 1) startIndex = 1;
//else if (startIndex - (dataList.Count - showCount) < 0) startIndex = (dataList.Count - showCount);
float overallProp = visualScope / overallLength; //可视比例
float maxY = content.transform.InverseTransformPoint(new Vector3(0, vector.y * overallLength, 0)).y; //最大高度
float minY = content.transform.InverseTransformPoint(new Vector3(0, vector.y * overallProp, 0)).y; //最小高度
int index = startIndex - 1; //虽然找到了开始位置,但是数组下标是从0开始的
int endIndex = startIndex + (dataList.Count - showCount);
List<int> uplist = new List<int>();
List<int> downList = new List<int>();
//清空不在范围内的数据存到队列中
foreach (int key in itemDictionary.Keys)
{
//当前物体在可视范围之上
if (key < startIndex - 1&& key + ((columnCount * (rowCount + 1)))<dataList.Count)
{
uplist.Add(key);
}
//当前物体在可视范围之下
if (key > startIndex + (columnCount * (rowCount + 1)) -columnCount-1)
{
downList.Add(key);
}
}
//删除上面的表示物体往下滑了,
//我们要填充的是该位置往下拉可视范围数量
foreach (int cursor in uplist)
{
Transform trans;
if (itemDictionary.TryGetValue(cursor, out trans))
{
itemDictionary.Remove(cursor);
int row = cursor / columnCount + (columnCount * (rowCount + 1)) / columnCount; //拉到第几行
int pos = cursor + (columnCount * (rowCount + 1));
float colum = -(row * (itemHeight + rowDistance) + itemHeight / 2 + rowDistance); //计算出该行位置
if ((columnCount * (rowCount + 1)) + cursor < dataList.Count)
{
trans = setElement(trans, dataList[(columnCount * (rowCount + 1)) + cursor]);
trans.localPosition = new Vector2(trans.localPosition.x, colum);
itemDictionary.Add(pos, trans);
}
}
}
//删除上面的表示物体往下滑了,
//我们要填充的是该位置往下拉可视范围数量
foreach (int cursor in downList)
{
Transform trans;
if (itemDictionary.TryGetValue(cursor, out trans))
{
itemDictionary.Remove(cursor);
int row = cursor / columnCount - (columnCount * (rowCount + 1)) / columnCount; //拉到第几行
int pos = cursor - (columnCount * (rowCount + 1));
float colum = -(row * (itemHeight + rowDistance) + itemHeight / 2 + rowDistance); //计算出该行位置
trans = setElement(trans, dataList[cursor-(columnCount * (rowCount + 1))]);
trans.localPosition = new Vector2(trans.localPosition.x, colum);
itemDictionary.Add(pos, trans);
}
}
}
///
/// 获取到要从第几个位置开始显示
/// 这里的做法就是最开始的位置减去当前位置
/// 往下滑值越低,往上滑值越高。
/// (初始位置-当前位置)/(item垂直距离+item高度)+1 = 从第几行开始显示
/// 行数*3+1
///
///
public int GetShowIndex()
{
float startPos = contentStartPos;
float currentPos = content.localPosition.y;
int line = ((int)((content.localPosition.y - startPos) / (itemHeight + rowDistance)) + 1);
int startIndex = line * columnCount - columnCount + 1;
return startIndex;
}
///
/// 获取子物体
///
///
///
public Transform GetItem(string data)
{
Transform itemTrans = null;
itemTrans = GameObject.Instantiate(itemTransform.gameObject).transform;
itemTrans.parent = content.transform;
itemTrans.gameObject.SetActive(true);
itemTrans.Find("Text").GetComponent<Text>().text = data;
itemTrans.GetComponent<RectTransform>().anchorMin = new Vector2(0, 1);
itemTrans.GetComponent<RectTransform>().anchorMax = new Vector2(0, 1);
return itemTrans;
}
}
因为继承MonoBehaviour不能直接做泛型类,所以多做了一个类MList
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MList : MonoBehaviour {
public float rowDistance; //行距
public float columnDistance; //列距
public void SetParam<T>(List<T> list, BaseList<T>.SetElement setElement)
{
BaseList<T> baseList = new BaseList<T>();
baseList.SetParam(list,setElement,transform,rowDistance,columnDistance);
}
}
使用的时候比较简单,把数据列表和设置Item的方法传递给列表即可显示
public class Person
{
public string name;
public int level;
public Person(string name,int level)
{
this.name = name;
this.level = level;
}
}
public class UIController : MonoBehaviour {
public MList mList;
void Start () {
List<Person> personList = new List<Person>();
for (int i = 0; i < 100; i++)
{
personList.Add(new Person("张三" + i, i));
}
mList = GetComponent<MList>();
mList.SetParam(personList, SetEnement);
}
public Transform SetEnement(Transform item, Person itemData)
{
item.Find("Name").GetComponent<Text>().text = itemData.name;
item.Find("Level").GetComponent<Text>().text = itemData.level+"";
return item.transform;
}
}