UIScrollView复用节点示例
发布日期:2021-06-30 19:39:12 浏览次数:2 分类:技术文章

本文共 2011 字,大约阅读时间需要 6 分钟。

重要脚本:UIPanel,UIScrollView,UIDragScrollView,UIWrapContent

记得item挂UIDragScrollView和BoxCollider哦

如下图,先把物体和脚本弄好

ReuseScroll就是自己写的复用脚本了

代码如下:

using UnityEngine;using System.Collections;using System.Collections.Generic;public class ReuseScroll : MonoBehaviour{    ///     /// 数据类    ///     public class MyData    {        public MyData(string name)        {            this.name = "name_" + name;        }        public string name;    }    public UIWrapContent wrapContent;    private Dictionary
m_index2Item = new Dictionary
(); ///
/// 数据列表 /// private List
m_data = new List
(); protected void Start() { InitData(); //启动wrapContent// wrapContent.enabled = true; //实现复用的托管方法// wrapContent.onInitializeItem = (go, wrapIndex, realIndex) => { realIndex = -realIndex; if (!m_index2Item.ContainsKey(realIndex)) { m_index2Item.Add(realIndex, go); } var actv = realIndex >= 0 && m_data.Count > realIndex; go.SetActive(actv); if (actv) go.GetComponentInChildren
().text = m_data[realIndex].name; }; } protected void Update() { //按A键添加数据并更新列表// if (Input.GetKeyDown(KeyCode.A)) { var index = m_data.Count; AddData(new MyData(index.ToString())); if (m_index2Item.ContainsKey(index)) { var go = m_index2Item[index]; if (go.transform.localPosition.y <= 0) { go.SetActive(true); go.GetComponentInChildren
().text = m_data[index].name; } } } } ///
/// 初始化数据 /// private void InitData() { for (int i = 0; i < 4; ++i) { m_data.Add(new MyData(i.ToString())); } } ///
/// 添加数据 /// private void AddData(MyData data) { m_data.Add(data); }}

效果如下,只需要几个item,复用可以显示无限个item,按A键即可插入新的数据并更新列表

希望大家有更好的办法的话,可以分享交流

转载地址:https://linxinfa.blog.csdn.net/article/details/55210490 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Unity 5 AudioMixer
下一篇:Unity发布的ios包在iphone上声音是从听筒里出来的问题

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月17日 02时21分13秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章