FancyCellGroup.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * FancyScrollView (https://github.com/setchi/FancyScrollView)
  3. * Copyright (c) 2020 setchi
  4. * Licensed under MIT (https://github.com/setchi/FancyScrollView/blob/master/LICENSE)
  5. */
  6. using UnityEngine;
  7. using System.Linq;
  8. namespace FancyScrollView
  9. {
  10. /// <summary>
  11. /// 複数の <see cref="FancyCell{TItemData, TContext}"/> を持つセルグループ実装するための抽象基底クラス.
  12. /// </summary>
  13. /// <typeparam name="TItemData">アイテムのデータ型.</typeparam>
  14. /// <typeparam name="TContext"><see cref="FancyCell{TItemData, TContext}.Context"/> の型.</typeparam>
  15. public abstract class FancyCellGroup<TItemData, TContext> : FancyCell<TItemData[], TContext>
  16. where TContext : class, IFancyCellGroupContext, new()
  17. {
  18. /// <summary>
  19. /// このグループで表示するセルの配列.
  20. /// </summary>
  21. protected virtual FancyCell<TItemData, TContext>[] Cells { get; private set; }
  22. /// <summary>
  23. /// このグループで表示するセルの配列をインスタンス化します.
  24. /// </summary>
  25. /// <returns>このグループで表示するセルの配列.</returns>
  26. protected virtual FancyCell<TItemData, TContext>[] InstantiateCells()
  27. {
  28. return Enumerable.Range(0, Context.GetGroupCount())
  29. .Select(_ => Instantiate(Context.CellTemplate, transform))
  30. .Select(x => x.GetComponent<FancyCell<TItemData, TContext>>())
  31. .ToArray();
  32. }
  33. /// <inheritdoc/>
  34. public override void Initialize()
  35. {
  36. Cells = InstantiateCells();
  37. Debug.Assert(Cells.Length == Context.GetGroupCount());
  38. for (var i = 0; i < Cells.Length; i++)
  39. {
  40. Cells[i].SetContext(Context);
  41. Cells[i].Initialize();
  42. }
  43. }
  44. /// <inheritdoc/>
  45. public override void UpdateContent(TItemData[] contents)
  46. {
  47. var firstCellIndex = Index * Context.GetGroupCount();
  48. for (var i = 0; i < Cells.Length; i++)
  49. {
  50. Cells[i].Index = i + firstCellIndex;
  51. Cells[i].SetVisible(i < contents.Length);
  52. if (Cells[i].IsVisible)
  53. {
  54. Cells[i].UpdateContent(contents[i]);
  55. }
  56. }
  57. }
  58. /// <inheritdoc/>
  59. public override void UpdatePosition(float position)
  60. {
  61. for (var i = 0; i < Cells.Length; i++)
  62. {
  63. Cells[i].UpdatePosition(position);
  64. }
  65. }
  66. }
  67. }