嵌套的ContentSizeFitter刷新

嵌套的ContentSizeFitter刷新

在做编辑器的时候,有些配置选项需要有可以折叠展开这个功能,如图所示:

我这边内容布局用了ContentSizeFitter这个组件,这个东西刷新需要隔一帧,我每个一帧给ContentSizeFitter刷新一次,发现这个虽然可以实现正确刷新显示,但是会闪一下。之后看了宣雨松大神的这篇文章 Unity3D研究院之ContentSizeFitter同步立即响应回调,改成了同步刷新就不闪了!

IEnumerator Refresh(Transform trans = null)
{
    if (trans != null)
    {
        //yield return null;
        while (trans != null)
        {
            ContentSizeFitter csf = trans.GetComponent<ContentSizeFitter>();
            if (csf)
            {
                // 加上这一句Rebuild
                 LayoutRebuilder.ForceRebuildLayoutImmediate(trans.GetComponent<RectTransform>());
                // 之前的做法
                //csf.enabled = false;
                //csf.enabled = true;
                //yield return null;
            }
            trans = trans.parent;
        }
        yield break;
    }

    GameObject go = GameObject.Find("UICanvas");
    Transform t = go.transform.Find("ScrollView/Viewport/Content");
    ContentSizeFitter[] coms = t.GetComponentsInChildren<ContentSizeFitter>();
    foreach (var item in coms)
    {
        LayoutRebuilder.ForceRebuildLayoutImmediate(trans.GetComponent<RectTransform>());
        //item.enabled = false;
        //item.enabled = true;
        //yield return null;
    }
}
原文地址:https://www.cnblogs.com/woodjay/p/12452847.html