今天碰到個需求是爲一個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,致使告終果不對。