ScrollView.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 System;
  7. using System.Collections.Generic;
  8. using UnityEngine;
  9. using EasingCore;
  10. namespace FancyScrollView.FocusOn
  11. {
  12. class ScrollView : FancyScrollView<ItemData, Context>
  13. {
  14. [SerializeField] Scroller scroller = default;
  15. [SerializeField] GameObject cellPrefab = default;
  16. Action<int,bool> onSelectionChanged;
  17. protected override GameObject CellPrefab => cellPrefab;
  18. protected override void Initialize()
  19. {
  20. base.Initialize();
  21. Context.OnCellClicked = onClick;
  22. scroller.OnValueChanged(UpdatePosition);
  23. scroller.OnSelectionChanged(UpdateSelection);
  24. }
  25. void UpdateSelection(int index)
  26. {
  27. if (Context.SelectedIndex == index)
  28. {
  29. return;
  30. }
  31. Context.SelectedIndex = index;
  32. Refresh();
  33. onSelectionChanged?.Invoke(index,false);
  34. }
  35. public void UpdateData(IList<ItemData> items)
  36. {
  37. UpdateContents(items);
  38. scroller.SetTotalCount(items.Count);
  39. }
  40. public void OnClickEvent(Action<int> OnCellClicked) {
  41. }
  42. public void OnSelectionChanged(Action<int,bool> callback)
  43. {
  44. onSelectionChanged = callback;
  45. }
  46. public void SelectNextCell()
  47. {
  48. int nextIndex = Context.SelectedIndex + 4;
  49. int index = nextIndex < ItemsSource.Count ? nextIndex : nextIndex - ItemsSource.Count;
  50. // Debug.LogWarning("nextIndex:" + nextIndex+ ",index:"+ index + ",ItemsSource.Count:"+ ItemsSource.Count);
  51. //翻页(4个一组)
  52. SelectCell(index);
  53. }
  54. public void SelectPrevCell()
  55. {
  56. int nextIndex = Context.SelectedIndex - 4;
  57. int index = nextIndex >= 0 ? nextIndex : ItemsSource.Count + nextIndex;
  58. // Debug.LogWarning("nextIndex:" + nextIndex + ",index:" + index + ",ItemsSource.Count:" + ItemsSource.Count);
  59. SelectCell(index);
  60. }
  61. public void SelectCell(int index,bool bScrollTo = true)
  62. {
  63. if (index < 0 || index >= ItemsSource.Count || index == Context.SelectedIndex)
  64. {
  65. //if (index == Context.SelectedIndex) {
  66. // onSelectionChanged?.Invoke(index,true);
  67. //}
  68. return;
  69. }
  70. UpdateSelection(index);
  71. if(bScrollTo)
  72. scroller.ScrollTo(index, 0.35f, Ease.OutCubic);
  73. }
  74. public void onClick(int index, bool bSelectedAndNav = true) {
  75. Context.SelectedIndex = index;
  76. Refresh();
  77. //点击按钮算触发
  78. onSelectionChanged?.Invoke(index, bSelectedAndNav);
  79. }
  80. }
  81. }