註冊監聽事件
主要使用的是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;
}