UGUI创建滑动列表步骤
1、创建一个panel,命名moveLayer,添加mask组件进行遮罩裁剪,添加scrollRect进行滑动。
2、为moveLayer创建一个容器也是panel,为容器命名content,在容器content里面添加layout组件,并把content设置到scrollRect里面;添加小孩的长度和高度要动态改变容器的宽高,才可以进行滑动。
滑动原理:主要是通过有滑动事件的moveLayer层移动,然后在中间层content添加小孩。滑动的时候,content相对父类坐标也跟着变动;
UGUI中可以直接使用scrollview进行创建,它已经为我们刚刚的组件设置好了,为content里面添加layout组件,代码中根据添加小孩的长度和高度要动态改变容器的宽高或者添加content size fitter组件帮助自适应宽高。
如上述操作,我们在代码封装组件tableView,实现动态创建cell,减少消耗。并实现多行多列,自动适应宽高。主要思想是通过,监听scrollRect的滑动事件来进行操作。
直接上代码:
<pre name="code" class="csharp">using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// @desc: 动态创建滑动列表,通过ugui5.3.6 通过创建Scroll View
/// @author: Rambo
/// @use 必须初始化scrollRect,content,itemPrefab,其他public参数按需初始;
/// @use 使用代码添加组件时,调用InitTableView进行初始化
/// @use 调用InitList创建tableView, setItemCall回调创建
/// </summary>
[DisallowMultipleComponent]
public class TableView : MonoBehaviour
{
public enum Arrangement
{
Horizontal,
Vertical,
}
/// <summary>
/// 选择滑动方向
/// </summary>
public Arrangement arrangement = Arrangement.Vertical;
/// <summary>
/// item刷新回调,声明了一个Delegate对象
/// </summary>
public Action<GameObject, int> SetItemCall;
/// <summary>
/// 设置行列,根据方向,垂直滑动为列,横向滑动为行
/// </summary>
[Range(1, 50)]
public int maxPerLine = 1;
/// <summary>
/// cells的宽间距
/// </summary>
[Range(0, 50)]
public float cellWidthSpace = 0f;
/// <summary>
/// cells的高间距
/// </summary>
[Range(0, 50)]
public float cellHeightSpace = 0f;
/// <summary>
/// 可见区域显示
/// </summary>
[Range(0, 30)]
public int viewCount = 5;
public ScrollRect scrollRect;
public RectTransform content;
public GameObject itemPrefab;
private float cellWidth = 200f; //cells的宽
private float cellHeight = 200f; //cells的高
private int dataCount; //创建最大数量
private int curScrollPerLineIndex = -1; //当前滑动下标
private float offx; //位置偏移量x
private float offy; //位置偏移量y
private List<TableViewItem> listItem = new List<TableViewItem>(); //存储显示的cells
private Queue<TableViewItem> unUseItem = new Queue<TableViewItem>();//存储删除的cells
#region 初始化处理
/// <summary>
/// 检测是否为空值
/// </summary>
private bool CheckArgeIsNull()
{
if (content == null)
{
Debug.LogError("content null");
return true;
}
if (scrollRect == null)
{
Debug.LogError("scrollRect null");
return true;
}
if (itemPrefab == null)
{
Debug.LogError("itemPrefab null");
return true;
}
cellWidth = itemPrefab.GetComponent<RectTransform>().sizeDelta.x;