注册监听事件
主要使用的是IComparer接口 Compare方法, 此方法支持排序比较
其次 可以使用transform.SetAsFirstSibling()函数,将这个物体移到其父物体列表下的第一个。
如果直接使用transform.SetParent(),那么这个物体将会变成其父物体列表中的最后一个顺序。
然后 通过for循环 进行升序降序
Sort.onClick.AddListener(() =>
{
List<addess> addess = new List<addess>();
Dictionary<addess, Transform> SortDic = new Dictionary<addess, Transform>();
for (int i = 0; i < Content.childCount; i++)
{
var trans = Content.GetChild(i);
SortDic[trans.GetComponent<CommonAdress>().addess] = trans;
addess.Add(trans.GetComponent<CommonAdress>().addess);
}
UpSort = !UpSort;
addess.Sort(new ComparePersonByAgeDown());
StringBuilder stringBuilder = new StringBuilder();
if (UpSort)
{
Sort.transform.LocalScaleY(1);
for (int i = 0; i < addess.Count; i++)
{
SortDic[addess[i]].SetAsFirstSibling();
}
}
else
{
Sort.transform.LocalScaleY(-1);
Debug.LogError(addess.Count);
// addess.Sort(new ComparePersonByAgeUp());
for (int i = addess.Count - 1; i >= 0; i--)
{
SortDic[addess[i]].SetAsFirstSibling();
}
}
});
public class ComparePersonByAgeDown : IComparer<addess>
{
public int Compare(addess x, addess y)
{
if (x == null && y == null) return 0;
if (x == null) return -1;
if (y == null) return 1;
if (x.Price < y.Price) return -1;
if (x.Price > y.Price) return 1;
return 0;
}
}
[System.Serializable]
public class addess
{
public string ImagePath;
public string Name;
public int Price;
public int Reviews;
public float Star;
}