您的位置:首页 > 产品设计 > UI/UE

使用UGUI ScrollView 排列不规则内容元素实现滑动效果

2017-07-14 15:09 891 查看
在开发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 () {

}
4000

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: