NGUI学习笔记(二):UIWrapCotent实现循环滚动

发表于2018-06-05
评论1 3.2k浏览
做UI的时候经常会做一些列表来显示商品啦,任务什么的,而且当这些列表数量很多,一页显示不完的时候,又会使用UIScrollView,这样虽然实现了滑动显示界面,但是当列表数量过多或者每个列表元素过多时,就会在初始化列表和滑动列表时导致程序卡顿。其实细想一下,每个列表的显示基本一样,完全可以重用的,于是NGUI里有了这个UIWrapContent脚本。

UIWrapContent的原理大致就是初始化的时候显示一页的元素,当滑动这一页的时候,位于首端或者尾端的元素会滑出显示区域,然后再把滑出显示区域的元素移动到本页的末端,同时改变其显示,这样就可以重复使用现有的几个元素来做显示。

上面给大家介绍了UIWrapCotent的原理,下面就来介绍下怎么使用UIWrapCotent实现循环滚动的,

先看一下目标效果(只用了6个Item哟):

动态效果

下面来搭建基础场景:

新建一个脚本,把它挂到场景中的Container上:
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// This script makes it possible for a scroll view to wrap its content, creating endless scroll views.
/// Usage: simply attach this script underneath your scroll view where you would normally place a UIGrid:
/// 
/// + Scroll View
/// |- UIWrappedContent
/// |-- Item 1
/// |-- Item 2
/// |-- Item 3
/// </summary>
[AddComponentMenu("NGUI/Custom/Wrap Content")]
public class UICustomWrapContent : UIWrapContent
{
    protected override void Start ()
    {
        base.Start ();
    }
    /// <summary>
    /// Want to update the content of items as they are scrolled? Override this function.
    /// </summary>
    protected override void UpdateItem (Transform item, int index)
    {
        if (onInitializeItem == null) 
        {
            onInitializeItem += InitializeItem;
        }
        else
        {
            int realIndex = (mScroll.movement == UIScrollView.Movement.Vertical) ?
                Mathf.RoundToInt(item.localPosition.y / itemSize):
                Mathf.RoundToInt(item.localPosition.x / itemSize);
            onInitializeItem(item.gameObject, index, realIndex);
        }
    }
    void InitializeItem(GameObject go,int index,int realIndex)
    {
        //Debug.LogFormat ("go.name =={0} index =={1}  realIndex == {2}",go.name,index,realIndex);
        realIndex = Mathf.Abs (realIndex);
        Transform child = transform.GetChild (index);
        UILabel rangeLbl = child.FindChild ("Range").GetComponent<UILabel> ();
        UILabel nameLbl = child.FindChild ("Name").GetComponent<UILabel> ();
        rangeLbl.text = (realIndex+1).ToString();
        nameLbl.text = "社会你"+(index).ToString()+"哥";
    }
}

注意这里的设定:

CullContent作者的解释:
Whether the content will be automatically culled. Enabling this will improve performance in scroll views that contain a lot of items.

最后一处设定:

注意设定的初始Value为0,并且Direction为Top To Bottom

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

1个评论

  • 默然-alex 2019-07-15 1楼
    很棒,点击事件怎么处理?谢谢