Advertisement
Kozjar

Untitled

Mar 11th, 2022
1,125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | None | 0 0
  1. public class Column<T>
  2. {
  3.     public string Header;
  4.     public Func<T, string> GetValue;
  5.     public int Width;
  6.  
  7.     public Column(string header, Func<T, string> getValue, int width = 1)
  8.     {
  9.         Header = header;
  10.         GetValue = getValue;
  11.         Width = width;
  12.     }
  13. }
  14.  
  15. public class Cell : MonoBehaviour
  16. {
  17.     [SerializeField] private Text _text;
  18.     [SerializeField] private LayoutElement _layoutElement;
  19.    
  20.     public string Text { set => _text.text = value; }
  21.     public int Width { set => _layoutElement.flexibleWidth = value; }
  22.  
  23.     private void Start()
  24.     {
  25.         _layoutElement.preferredWidth = 0;
  26.     }
  27. }
  28.  
  29. public class Row<T> : MonoBehaviour where T : struct
  30. {
  31.     [SerializeField] private Cell cellPrefab;
  32.  
  33.     private List<Cell> _cells = new List<Cell>();
  34.     private List<Column<T>> _columns = new List<Column<T>>();
  35.  
  36.     public List<Column<T>> Columns
  37.     {
  38.         set
  39.         {
  40.             _columns = value;
  41.            
  42.             RemoveCells();
  43.             CreateCells();
  44.         }
  45.     }
  46.  
  47.     public void UpdateCells(T? data = null)
  48.     {
  49.         for (int i = 0; i < _columns.Count; i++)
  50.         {
  51.             _cells[i].Text = data == null ? _columns[i].Header : _columns[i].GetValue((T)data);
  52.         }
  53.     }
  54.  
  55.     private void RemoveCells()
  56.     {
  57.         foreach (GameObject cell in transform)
  58.         {
  59.             Destroy(cell);
  60.         }
  61.         _cells.Clear();
  62.     }
  63.  
  64.     private void CreateCells()
  65.     {
  66.         foreach (Column<T> column in _columns)
  67.         {
  68.             var cell = Instantiate(cellPrefab, transform);
  69.             cell.Width = column.Width;
  70.             _cells.Add(cell);
  71.         }
  72.     }
  73. }
  74.  
  75. // Пример использования
  76. // Описание колонок
  77. private readonly List<Column<ProductMarketData>> _columns = new List<Column<ProductMarketData>>()
  78. {
  79.     new Column<ProductMarketData>("product", data => data.name, 2),
  80.     new Column<ProductMarketData>("price", data => data.price.ToString("0.00"), 2),
  81.     new Column<ProductMarketData>("sellDemand", data => data.sellDemand.ToString("0.00")),
  82. };
  83.  
  84. // Создание строки
  85. var row = Instantiate(rowPrefab, tableContent.transform);
  86.  
  87. row.Columns = _columns;
  88.  
  89. // Обновление строки
  90. row.UpdateCells(data);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement