UIGrid的CustomSort使用

今天碰到个需求是为一个UIGrid实现一个自定义排序。html

实现的话有2种方式,第一能够在将数据生成界面以前,排好序,而后传递给界面,生成出来的就是已经排好序的。这种实现方式比较自由,对多种数据结构能够自定义实现,好比说LINQ,List等等均可以实现。网页上搜索到的基本也均可以实现这种排序。HERE数据结构

第二能够使用NGUI提供的接口。OnCustomerSort。spa

NGUI的自定义排序的原理剖析:code

List<Transform> list = new List<Transform>();

UIGrid内部使用的数据结构是List<Transform>。orm

     // Sort the list using the desired sorting logic
        if (sorting != Sorting.None && arrangement != Arrangement.CellSnap)
        {
            if (sorting == Sorting.Alphabetic) list.Sort(SortByName);
            else if (sorting == Sorting.Horizontal) list.Sort(SortHorizontal);
            else if (sorting == Sorting.Vertical) list.Sort(SortVertical);
            else if (onCustomSort != null) list.Sort(onCustomSort);
            else Sort(list);
        }

使用的排序的核心代码如上,其实就是list的排序(如上)。依据不一样的排序类型调用不一样的方法。htm

   /// <summary>
    /// Custom sort delegate, used when the sorting method is set to 'custom'.
    /// </summary>

    public System.Comparison<Transform> onCustomSort;

onCustomSort是一个transform类型实现了比较接口的委托。blog

SO,其实UIGrid就是使用了list的这个接口(上图)的排序。而后使用委托将接口暴露出来。排序

实现:1.将UIGrid的排序类型设置成custom。接口

2.添加委托的方法:get

Grid.onCustomSort += customSort;

3.实现委托的方法:

int customSort(Transform left, Transform right){}

 委托中传入的参数是transfrom,能够直接调用GetComponent来得到组件来进行比较。

最后说一下写的时候遇到的一个坑:接口返回的是int。大于:正数,等于:0,小于:负数。敲代码的时候考虑,其实只须要保证2种,而后写出了 return left>right?1:-1; 

的代码,以后结果一直不正确。仔细思考之发现,等于这种状态其实不能省略。如上的代码若是是相等的2个都会返回-1,致使告终果不对。

相关文章
相关标签/搜索