Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Column<T>
- {
- public string Header;
- public Func<T, string> GetValue;
- public int Width;
- public Column(string header, Func<T, string> getValue, int width = 1)
- {
- Header = header;
- GetValue = getValue;
- Width = width;
- }
- }
- public class Cell : MonoBehaviour
- {
- [SerializeField] private Text _text;
- [SerializeField] private LayoutElement _layoutElement;
- public string Text { set => _text.text = value; }
- public int Width { set => _layoutElement.flexibleWidth = value; }
- private void Start()
- {
- _layoutElement.preferredWidth = 0;
- }
- }
- public class Row<T> : MonoBehaviour where T : struct
- {
- [SerializeField] private Cell cellPrefab;
- private List<Cell> _cells = new List<Cell>();
- private List<Column<T>> _columns = new List<Column<T>>();
- public List<Column<T>> Columns
- {
- set
- {
- _columns = value;
- RemoveCells();
- CreateCells();
- }
- }
- public void UpdateCells(T? data = null)
- {
- for (int i = 0; i < _columns.Count; i++)
- {
- _cells[i].Text = data == null ? _columns[i].Header : _columns[i].GetValue((T)data);
- }
- }
- private void RemoveCells()
- {
- foreach (GameObject cell in transform)
- {
- Destroy(cell);
- }
- _cells.Clear();
- }
- private void CreateCells()
- {
- foreach (Column<T> column in _columns)
- {
- var cell = Instantiate(cellPrefab, transform);
- cell.Width = column.Width;
- _cells.Add(cell);
- }
- }
- }
- // Пример использования
- // Описание колонок
- private readonly List<Column<ProductMarketData>> _columns = new List<Column<ProductMarketData>>()
- {
- new Column<ProductMarketData>("product", data => data.name, 2),
- new Column<ProductMarketData>("price", data => data.price.ToString("0.00"), 2),
- new Column<ProductMarketData>("sellDemand", data => data.sellDemand.ToString("0.00")),
- };
- // Создание строки
- var row = Instantiate(rowPrefab, tableContent.transform);
- row.Columns = _columns;
- // Обновление строки
- row.UpdateCells(data);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement