Scrollview优化列表组件

实现原理

  • 基于队列实现
  • 根据当前Content视口的大小计算出视口里最多存在的Item
  • 根据位置不断更新当前显示的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 基于UGUI ScrollView组件的高性能列表组件。对性能有高要求的列表组件可以考虑使用该组件
/// </summary>
[RequireComponent(typeof(ScrollRect))]
public class ScrollViewList : MonoBehaviour
{
public enum ELayoutType
{
/// <summary>
/// 垂直列表
/// </summary>
VERTICAL,
/// <summary>
/// 横向列表
/// </summary>
HORIZONTAL,
}

/// <summary>
/// 布局方式
/// </summary>
public ELayoutType layoutType = ELayoutType.VERTICAL;

/// <summary>
/// 列表项的间隔
/// </summary>
public float itemGap = 0;

/// <summary>
/// 滚动组件
/// </summary>
ScrollRect _scrollRect;

/// <summary>
/// 存储位置
/// </summary>
RectTransform _content;

/// <summary>
/// 列表项的Prefab,默认Content第一个物体
/// </summary>
GameObject _itemPrefab;

/// <summary>
/// 列表项的大小
/// </summary>
Vector2 _itemSize;

/// <summary>
/// 生成的列表项示例列表
/// </summary>
List<GameObject> _items = new List<GameObject>();

/// <summary>
/// 列表视口
/// </summary>
Rect _viewport;

/// <summary>
/// 视口可见的最大列表项数量
/// </summary>
int _itemMaxCount;

/// <summary>
/// 列表的数据
/// </summary>
object[] _datas;

/// <summary>
/// 列表项更新的回调
/// </summary>
Action<int, object, GameObject> _onItemUpdate;

/// <summary>
/// 列表项占用的空间
/// </summary>
float _itemSpace = 0;

/// <summary>
/// Item 的缓存池
/// </summary>
Queue<GameObject> _itemPool = new Queue<GameObject>();

/// <summary>
/// 正在显示的列表项
/// </summary>
Dictionary<int, GameObject> _showedDic = new Dictionary<int, GameObject>();

private void Awake()
{
_scrollRect = GetComponent<ScrollRect>();
_viewport = _scrollRect.GetComponent<RectTransform>().rect;
_content = transform.Find("Viewport/Content").GetComponent<RectTransform>();
_itemPrefab = _content.GetChild(0).gameObject;
var rt = _itemPrefab.GetComponent<RectTransform>();
_itemSize = rt.sizeDelta;
var topLeft = new Vector2(0, 1);
rt.pivot = topLeft;
rt.anchorMin = topLeft;
rt.anchorMax = topLeft;
_itemPrefab.SetActive(false);
SetItemGap(itemGap);
}


#region 测试

//public void Update()
//{
// if (Input.GetKeyDown(KeyCode.A))
// {
// SetItemUpdata(OnItemUpDate);
// SetItemGap(10);
// List<string> ls = new List<string>();
// for (int i = 0; i < 1000000; i++)
// {
// ls.Add("current"+i);
// }
// SetData(ls.ToArray());
// }
//}
#endregion

/// <summary>
/// 设置列表项间隙
/// </summary>
/// <param name="gap"></param>
public void SetItemGap(float gap)
{
itemGap = gap;
SetData(_datas);
}



private void OnEnable()
{
_scrollRect.onValueChanged.AddListener(OnScroll);
}

public void SetData(object[] data)
{
Clear();

switch (layoutType)
{
case ELayoutType.VERTICAL:
_itemSpace = _itemSize.y + itemGap;
_itemMaxCount = Mathf.CeilToInt(_viewport.height / _itemSpace) + 1;
break;
case ELayoutType.HORIZONTAL:
_itemSpace = _itemSize.x + itemGap;
_itemMaxCount = Mathf.CeilToInt(_viewport.width / _itemSpace) + 1;
break;
}

_datas = data;
if (data != null)
{
_refreRate = 0.1f / data.Length;
}
Debug.LogError(_refreRate);

if (null == _datas || _datas.Length == 0)
{
return;
}
int count = _datas.Length;
SetContentSize((_itemSpace * count) - itemGap);
RefreshUI();
}

/// <summary>
/// 显示指定索引位置的列表项
/// </summary>
/// <param name="idx"></param>
public void ShowItem(int idx)
{
if(null == _datas)
{
return;
}
var pos = _itemSpace * idx;
SetContentPos(pos);
}

void SetContentSize(float size)
{
var contentSize = _content.sizeDelta;

switch (layoutType)
{
case ELayoutType.VERTICAL:
contentSize.y = size;
break;
case ELayoutType.HORIZONTAL:
contentSize.x = size;
break;
}

_content.sizeDelta = contentSize;
}

void SetContentPos(float pos)
{
var contentPos = _content.localPosition;

switch (layoutType)
{
case ELayoutType.VERTICAL:
contentPos.y = pos;
break;
case ELayoutType.HORIZONTAL:
contentPos.x = -1 * pos;
break;
}

_content.localPosition = contentPos;
}

public void Clear()
{
for(int i = 0; i < _items.Count; i++)
{
GameObject.Destroy(_items[i]);
}
_showedDic.Clear();
_items.Clear();
_itemPool.Clear();
_datas = null;
_scrollRect.velocity = Vector2.one;

SetContentPos(0);

switch (layoutType)
{
case ELayoutType.VERTICAL:
SetContentSize(_viewport.height);
break;
case ELayoutType.HORIZONTAL:
SetContentSize(_viewport.width);
break;
}
}

private void OnDisable()
{
_scrollRect.onValueChanged.RemoveListener(OnScroll);
}

/// <summary>
/// 当前位置
/// </summary>
private Vector2 _currentPos;

private float _refreRate;

private void OnScroll(Vector2 v)
{
if (CompareVector2(v, _currentPos ,_refreRate))
{
return;
}

_currentPos = v;
RefreshUI();
}

private bool CompareVector2(Vector2 v1,Vector2 v2,float dis)
{
return Mathf.Abs(v1.x - v2.x) < dis && Mathf.Abs(v1.y - v2.y) < dis;
}


HashSet<int> updateNeedlessSet = new HashSet<int>();
Dictionary<int, GameObject> showedDic = new Dictionary<int, GameObject>();

/// <summary>
/// 刷新界面
/// </summary>
private void RefreshUI()
{
if( _datas == null)
{
return;
}

float localPos;
if(layoutType == ELayoutType.VERTICAL)
{
localPos = _content.localPosition.y;
}
else
{
localPos = -1 * _content.localPosition.x ;
}

//显示开始的索引
int startIdx = Mathf.FloorToInt(localPos / _itemSpace);
if(startIdx < 0)
{
startIdx = 0;
}

//Item 显示开始的位置
Vector2 pos = new Vector2(0f, startIdx * _itemSpace);

int endIdx = startIdx + _itemMaxCount;
if (endIdx > _datas.Length)
{
endIdx = _datas.Length;
}

HashSet<int> updateNeedlessSet = new HashSet<int>();
Dictionary<int, GameObject> showedDic = new Dictionary<int, GameObject>();

//找出可以不用更新的Item
foreach (var entry in _showedDic)
{
if(entry.Key >= startIdx && entry.Key < endIdx)
{
//不用更新的
updateNeedlessSet.Add(entry.Key);
showedDic.Add(entry.Key, entry.Value);
}
else
{
//加入缓存池
_itemPool.Enqueue(entry.Value);
}
}

_showedDic = showedDic;

for (int i = startIdx; i < endIdx; i++)
{
if(updateNeedlessSet.Contains(i))
{
//已经显示的可以忽略不处理
continue;
}

if(layoutType == ELayoutType.VERTICAL)
{
pos.x = 0f;
pos.y = -1 * i * _itemSpace;
}
else
{
pos.x = i * _itemSpace;
pos.y = 0f;
}

CreateItem(i, pos, _datas[i], _itemPool);
}
}

private void OnItemUpDate(int num, object data, GameObject item)
{
item.transform.Find("Text").GetComponent<Text>().text = (string)data;
}

public void SetItemUpdata(Action<int ,object,GameObject> ItemUpdata)
{
_onItemUpdate = ItemUpdata;
}




public GameObject CreateItem(int idx, Vector2 pos, object data, Queue<GameObject> itemPool)
{
GameObject go = null;
if(itemPool.Count > 0)
{
go = itemPool.Dequeue();
}
else
{
go = GameObject.Instantiate(_itemPrefab, _content);
go.name = "item" + idx;
_items.Add(go);
}

_showedDic.Add(idx, go);
go.transform.localPosition = pos;
go.SetActive(true);
_onItemUpdate?.Invoke(idx, data, go);
return go;
}
}