using System; using UnityEngine; namespace XGame.Framework.UI { public abstract class NestedView : INestedInternal, IDisposable where TController : class, IUIController where TViewModel : class, IUIViewModel { private UIContext _context; private IUINested _nested; private TViewModel _vm; private TController _controller; public TViewModel VM => _vm; public TController Ctrl => _controller; private Transform NestedTr => _nested.Tr; Vector3 INestedView.LocalPosition { get => NestedTr.localPosition; set => NestedTr.localPosition = value; } Vector3 INestedView.Position { get => NestedTr.position; set => NestedTr.position = value; } Vector3 INestedView.Rotation { get => NestedTr.rotation.eulerAngles; set => NestedTr.rotation = Quaternion.Euler(value); } IUINested INestedInternal.Nested => _nested; void INestedInternal.Init(UIContext context, IUINested nested, bool isStatic) { _context = context; _nested = nested; _vm = Activator.CreateInstance(); (_vm as IUIVMInternal).Init(nested, context); var controller =Activator.CreateInstance(); if (controller is IUIContextSetter contextSetter) { contextSetter.Context = _context; } if (controller is IUIViewModelSetter vmSetter) { vmSetter.ViewModel = _vm; } _controller = controller; //if (isStatic && nested.IsActiveSelf) //{ // Active = true; //} } void INestedInternal.EnableByParent(object intent) { Assert.IsFalse(Active, $"NestedView 子节点先于父节点激活. Transform: {_nested.Tr.name}"); if (!_nested.IsActiveInHierarchy) { return; } // nested节点自身是显示状态 Active = true; _controller.Enable(intent); (VM as IUIVMInternal).EnableChildren(intent); } void INestedInternal.DisableByParent() { if (!Active) return; Assert.IsFalse(_nested.IsActiveInHierarchy, $"NestedView 父节点还是显示状态. Transform: {_nested.Tr?.name ?? "NULL"}"); if (!_nested.IsActiveSelf) { return; } // 父节点已经隐藏, 但是 nested节点自身是显示状态 Active = false; (VM as IUIVMInternal).DisableChildren(); _controller.Disable(); } private bool _isActive; public bool Active { get => _isActive; private set { _isActive = value; //var ctrlGroup = (_context as IUIViewAdapter).CtrlGroup; //if (value) // ctrlGroup?.Add(_controller, false); //else // ctrlGroup?.Remove(_controller); } } public void Enable(object intent) { if (Active) return; _nested.SetActive(true); if (_nested.IsActiveInHierarchy) { // 已经在场景里显示,激活,否则由父节点统一激活 Active = true; _controller.Enable(intent); (VM as IUIVMInternal).EnableChildren(intent); } else { Log.Warn($"NestedView 父节点隐藏状态,无法激活子节点, Transform: {_nested.Tr.name}"); } } public void Disable() { if (!Active) return; _nested.SetActive(false); Active = false; // 隐藏嵌套的Nested (VM as IUIVMInternal).DisableChildren(); _controller.Disable(); } void IDisposable.Dispose() { //if (_isActive) //{ // 预防没有执行Disable() // Active = false; // _controller.OnDisable(); //} OnDispose(); (_controller as IDisposable)?.Dispose(); (_vm as IDisposable)?.Dispose(); _vm = null; _nested = default; _context = null; } protected abstract void OnDispose(); } }