1. 程式人生 > >使用UGUI ScrollView 排列不規則內容元素實現滑動效果

使用UGUI ScrollView 排列不規則內容元素實現滑動效果

在開發Unity專案中有時會遇到滑動檢視,這個一般實現方式都是使用UGUI元件ScrollView實現,搭配GridLayoutGroup,以及ContentSizeFitter實現,但是當專案中需要使用不規則內容元素動態載入的時候,GridLayoutGruop就變得不太適用。。。正好在專案中,遇到這個問題,我把我的做法分享一下,也算給自己記一個筆跡。
1,我的實現方式是,使用VerticalLayoutGroup,以及ContentSizeFitter,以及自己寫的一個類似ContentSizeFitter程式碼實現。
實現效果簡要說明:
這裡寫圖片描述

具體實現步驟圖示
步驟一:
這裡寫圖片描述


步驟二:
這裡寫圖片描述
步驟三:
這裡寫圖片描述
步驟四:
這裡寫圖片描述
步驟五:
這裡寫圖片描述
步驟六:計算ScrollView顯示區高度


using System.Collections;
using UnityEngine;


public class ListUIMng : MonoBehaviour {
    public GameObject prefab;
    public Transform content;
    // Use this for initialization


    void Start()
    {

        SizeInit();
    }
    // Update is called once per frame
void Update () { } private void OnGUI() { if (GUI.Button(new Rect(20,100,100,50),"新增道具")) { GameObject tool = GameObject.Instantiate(prefab); tool.transform.parent = content.GetChild(1); StartCoroutine(SetHight()); } if (GUI.Button(new
Rect(20, 300, 100, 50), "新增應用場景")) { GameObject scence = GameObject.Instantiate(prefab); scence.transform.parent = content.GetChild(content.childCount - 1); StartCoroutine(SetHight()); } } public void SizeInit() { StartCoroutine(SetHight()); } IEnumerator SetHight() { yield return new WaitForSeconds(0.1f); //採用高度累加的方式,避免動態加入元素,最後元素位置不重新整理問題(通過第一個元素和最後元素計算,重新整理延遲會出問題) float hight = 0; for (int i = 0; i < content.childCount; i++) { hight += content.GetChild(i).GetComponent<RectTransform>().sizeDelta.y; } Debug.Log("======hight==" + hight); RectTransform rect = content.GetComponent<RectTransform>(); rect.sizeDelta = new Vector2(rect.sizeDelta.x, hight); } }