NestedView.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using UnityEngine;
  3. namespace XGame.Framework.UI
  4. {
  5. public abstract class NestedView<TController, TViewModel> : INestedInternal, IDisposable
  6. where TController : class, IUIController
  7. where TViewModel : class, IUIViewModel
  8. {
  9. private UIContext _context;
  10. private IUINested _nested;
  11. private TViewModel _vm;
  12. private TController _controller;
  13. public TViewModel VM => _vm;
  14. public TController Ctrl => _controller;
  15. private Transform NestedTr => _nested.Tr;
  16. Vector3 INestedView.LocalPosition { get => NestedTr.localPosition; set => NestedTr.localPosition = value; }
  17. Vector3 INestedView.Position { get => NestedTr.position; set => NestedTr.position = value; }
  18. Vector3 INestedView.Rotation { get => NestedTr.rotation.eulerAngles; set => NestedTr.rotation = Quaternion.Euler(value); }
  19. IUINested INestedInternal.Nested => _nested;
  20. void INestedInternal.Init(UIContext context, IUINested nested, bool isStatic)
  21. {
  22. _context = context;
  23. _nested = nested;
  24. _vm = Activator.CreateInstance<TViewModel>();
  25. (_vm as IUIVMInitable).Init(nested, context);
  26. var controller =Activator.CreateInstance<TController>();
  27. if (controller is IUIContextSetter contextSetter)
  28. {
  29. contextSetter.Context = _context;
  30. }
  31. if (controller is IUIViewModelSetter vmSetter)
  32. {
  33. vmSetter.ViewModel = _vm;
  34. }
  35. _controller = controller;
  36. if (isStatic && nested.IsActiveSelf)
  37. {
  38. Active = true;
  39. }
  40. }
  41. private bool _isActive;
  42. public bool Active
  43. {
  44. get => _isActive;
  45. private set
  46. {
  47. _isActive = value;
  48. var ctrlGroup = (_context as IUIViewAdapter).CtrlGroup;
  49. if (value)
  50. ctrlGroup?.Add(_controller, false);
  51. else
  52. ctrlGroup?.Remove(_controller);
  53. }
  54. }
  55. public void Enable(object intent)
  56. {
  57. if (Active) return;
  58. Active = true;
  59. _nested.SetActive(true);
  60. if (_nested.IsActiveInHierarchy)
  61. { // 已经在场景里显示,自己激活Controller,否则由UIView统一激活
  62. _controller.Enable(intent);
  63. }
  64. }
  65. public void Disable()
  66. {
  67. if (!Active) return;
  68. Active = false;
  69. _nested.SetActive(false);
  70. _controller.Disable();
  71. }
  72. void IDisposable.Dispose()
  73. {
  74. //if (_isActive)
  75. //{ // 预防没有执行Disable()
  76. // Active = false;
  77. // _controller.OnDisable();
  78. //}
  79. OnDispose();
  80. (_controller as IDisposable)?.Dispose();
  81. _nested = default;
  82. _context = null;
  83. _vm = null;
  84. }
  85. protected abstract void OnDispose();
  86. }
  87. }