UI中实现一个抽屉式折叠面板
成果展示
Scene部分
主要包括两个部分:Option和Content。
option对应的是选项按钮;Content对应的是展开的内容;
这里由于此篇写法的问题。需要将option中Button从0开始依次编号。
物体请按照固定的距离进行摆放。
如Option中每个子物体的位置分别为(0,0,0)(0,-140,0)(0,-180,0)(0,-220,0);
Content中每个子物体的位置分别为(0,0,0)(0,-40,0)(0,-80,0)(0,-120,0);
可以看到未展开的两个选项按钮距离间隔为40;
中间有展开内容的两个选项按钮距离间隔为140;
脚本绑定在Collapse物体上
脚本部分
新建一个类,定义一些与业务无关的基本方法
public class BaseCollapse
{
private List<RectTransform> optionTransformList;
private List<Transform> contentTransformList;
private float optionStep;
private float contentStep;
/// <summary>
/// 通用的折叠面板操作
/// </summary>
/// <param name="optionTransformList">所有选项</param>
/// <param name="contentTransformList">所有内容</param>
/// <param name="optionStep">选项中间间隔</param>
/// <param name="contentStep">展开内容后,选项之间间隔</param>
public BaseCollapse(List<RectTransform> optionTransformList, List<Transform> contentTransformList, float optionStep, float contentStep)
{
this.contentTransformList = contentTransformList;
this.optionTransformList = optionTransformList;
this.optionStep = optionStep;
this.contentStep = contentStep-optionStep;
}
/// <summary>
/// 展开折叠面板的指定项
/// </summary>
/// <param name="id">指定项ID</param>
public void CollapseVisble(int id)
{
RectTransform optionTransform = optionTransformList[id];
Transform contentTransform = contentTransformList[id];
Vector2 optionPosition = optionTransform.anchoredPosition;
if (!contentTransform.gameObject.activeSelf)
{
foreach (var item in contentTransformList)
{
item.gameObject.SetActive(false);
}
contentTransform.gameObject.SetActive(true);
for (int i = id + 1; i < optionTransformList.Count; i++)
{
optionTransformList[i].anchoredPosition = new Vector2(optionPosition.x, optionTransformList[0].anchoredPosition.y - contentStep - optionStep * i);
}
for (int i = 1; i < id + 1; i++)
{
optionTransformList[i].anchoredPosition = new Vector2(optionPosition.x, optionTransformList[0].anchoredPosition.y - optionStep * i);
}
}
}
}
脚本绑定到物体,实例化BaseCollapse,传入相关的信息。
public class Collapse : MonoBehaviour
{
private List<RectTransform> optionTransform;
private List<Transform> contentTransform;
BaseCollapse baseCollapse;
private void Awake()
{
optionTransform = new List<RectTransform>();
Transform options = transform.Find("option");
for (int i = 0; i < options.childCount; i++)
{
optionTransform.Add(options.GetChild(i).GetComponent<RectTransform>());
}
contentTransform = new List<Transform>();
Transform content = transform.Find("content");
for (int i = 0; i < content.childCount; i++)
{
contentTransform.Add(content.GetChild(i));
}
for (int i = 0; i < optionTransform.Count; i++)
{
Button button = optionTransform[i].GetComponent<Button>();
button.onClick.AddListener(() =>
{
baseCollapse.CollapseVisble(int.Parse(button.name));
});
}
baseCollapse = new BaseCollapse(optionTransform, contentTransform, 40, 140);
}
}
标签:contentTransform,List,optionTransformList,Unity,UI,private,抽屉式,optionTransform,o
From: https://www.cnblogs.com/sitarblogs/p/18438801