Unity TreeView2



唔,之前的Treeview感觉不太好用,所以。。又写了个

代码在https://download.csdn.net/download/qq_17813937/10528783

每次改变节点状态都会从新计算节点坐标

    private void UpdatePos(TreeItemData data, int index = -1)
    {
        if (data != root)
        {
            if (data.target.gameObject.activeSelf)
            {
                if (!(index == 0 && data.parent.id == 0))
                {
                    if (index != 0) currentHeight += GetSpace(data);
                    else currentHeight += space;
                }
                data.target.localPosition = itemParent.localPosition - new Vector3(-data.indentLevel * indent - padding.x, currentHeight + padding.y);
                currentHeight += GetHeight(data);
            }
        }

        int count = data.childs.Count;
        for (int i = 0; i < count; i++)
        {
            UpdatePos(data.childs[i], i);
        }
    }


每次改变节点状态,都需要更新 conent的大小,以供滚动

    private void UpdateSize()
    {
        int count = items.Count;
        Vector2 max = Vector2.zero;
        for (int i = 0; i < count; i++)
        {
            if (!datas[i].isShow) continue;
            var tmp = items[i].transform as RectTransform;

            var size = new Vector2(tmp.localPosition.x, -tmp.localPosition.y) + tmp.sizeDelta;

            max.x = Mathf.Max(max.x, size.x);
            max.y = Mathf.Max(max.y, size.y);
        }
        conent.sizeDelta = new Vector2(max.x + padding.width, max.y + padding.height);
    }

使用方式

using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour 
{
    
	private void Awake()
	{
        var view = GetComponent<TreeView>();
        view.CustomsChildSize(0, new Vector2(200,30));
        view.CustomsSpace(0, 30);

        view.onClick = (item, isOpen) => {
            var target = item as CustomTreeItemData;
            target.toggle.isOn = isOpen;
            Debug.Log("点击了:"+item.name.text);
        };

        view.onHideItem = item => {
            var target = item as CustomTreeItemData;
            target.toggle.isOn = false;
        };

        view.onCreateItem = item => {
            if (item.childs.Count == 0)
            {
                var target = item as CustomTreeItemData;
                target.toggle.gameObject.SetActive(false);
            }
        };


        for (int i = 0; i < 10; i++)
        {
            view.AddData<CustomTreeItemData>(Random.Range(0,i), i, i.ToString());
        }
        view.Generate();
        view.AddItem<CustomTreeItemData>(9, 10, "666");
	}
    
}

public class CustomTreeItemData:TreeItemData
{
    public Toggle toggle;

    protected override void Init(Transform value)
    {
        toggle = target.GetComponentInChildren<Toggle>();
    }
}


猜你喜欢

转载自blog.csdn.net/qq_17813937/article/details/80959710