UGUI的Layout布局組件確實節省了我們很多代碼
如果不使用Layout組件
那么光在計算UI的布局上就要花費很大的功夫
特別是動態生成其組件的時候
當然,Layout組件在大多數時候是非常好用的
也有讓人頭疼的時候
比如,一個組件內需要展開或者折疊
這時,刷新不及時帶來的問題就出現了
比如展開時產生UI覆蓋
折疊時產生UI空隙
都是讓人頭大的問題
幸好Unity提供了一個強制刷新UI的方法
便將此問題完美解決了
LayoutRebuilder.ForceRebuildLayoutImmediate(recttransform);
參數為掛有Layout組件的recttransform
為了確保能夠正確的刷新
建議放在一個協程中,待幀結束后檢測一次,若沒有刷新再執行一次
IEnumerator UpdateLayout(RectTransform rect) { LayoutRebuilder.ForceRebuildLayoutImmediate(rect); yield return new WaitForEndOfFrame(); Vector3 vecScale = rect.localScale; float width = rect.rect.width; float height = rect.rect.height; while (rect.rect.width == 0) { Debug.Log(rect.rect.width); LayoutRebuilder.ForceRebuildLayoutImmediate(rect); yield return new WaitForEndOfFrame(); } }