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

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

2017-07-02 18:41 776 查看
通常我们使用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()+"哥";

}
}


注意这里的设定:



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