NGUI学习笔记(二):UIWrapCotent实现循环滚动(优化排行榜等效果)

来源:互联网 发布:ios 去掉数组小括号 编辑:程序博客网 时间:2024/06/17 06:11

通常我们使用NGUI的UIScrollView时,其内部挂载的子项并不会太多,但如果几百个甚至上千个,那么把它们统统实例化出来同时放到场景中便是很麻瓜的.

能不能让滚出ScrollView的Item重新被我们利用显示新的内容呢?
NGUI作者早就想到了这个问题.只需要重写UIWrapCotent.cs的UpdateItem函数就可以了.

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

下面来搭建基础场景:
搭建基础场景

新建一个脚本,把它挂到场景中的Container上:

//----------------------------------------------//            NGUI: Next-Gen UI kit// Copyright © 2011-2015 Tasharen Entertainment//----------------------------------------------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()+"哥";    }}

注意这里的设定:
设定1
CullContent作者的解释:
Whether the content will be automatically culled. Enabling this will improve performance in scroll views that contain a lot of items.
最后一处设定:
设定2
注意设定的初始Value为0,并且Direction为Top To Bottom