Net.Like.Xue.Tokyo/Assets/BITKit/Unity/Scripts/UX/Library/TabContainer.cs

87 lines
1.8 KiB
C#
Raw Normal View History

2024-11-03 16:42:23 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit.UX
{
public class TabContainer : VisualElement
{
public new class UxmlTraits:VisualElement.UxmlTraits
{
private readonly UxmlStringAttributeDescription _mTabPath = new ()
{
name = "TabPath",
};
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
var container = (TabContainer)ve;
container.TabPath = _mTabPath.GetValueFromBag(bag, cc);
}
}
public new class UxmlFactory : UxmlFactory<TabContainer, UxmlTraits> { }
public TabContainer()
{
2024-12-30 21:34:37 +08:00
RegisterCallback<AttachToPanelEvent>(RebuildOnEvent);
RegisterCallback<DetachFromPanelEvent>(RebuildOnEvent);
RegisterCallback<GeometryChangedEvent>(RebuildOnEvent);
RegisterCallback<BlurEvent>(RebuildOnEvent);
RegisterCallback<FocusEvent>(RebuildOnEvent);
2024-12-28 23:19:55 +08:00
}
2024-11-03 16:42:23 +08:00
public string TabPath
{
get=>_tabPath;
set
{
_tabPath = value;
2024-12-30 21:34:37 +08:00
Rebuild();
2024-11-03 16:42:23 +08:00
}
}
private string _tabPath;
private TabBar _tabBar;
private int _index;
2024-12-30 21:34:37 +08:00
private void RebuildOnEvent<T>(T evt)
2024-11-03 16:42:23 +08:00
{
Rebuild();
}
private void Rebuild()
{
if (_tabBar is not null)
{
_tabBar.OnTabChanged -= OnTabChanged;
}
2024-12-30 21:34:37 +08:00
var p = parent;
while (p is not null)
2024-11-03 16:42:23 +08:00
{
2024-12-30 21:34:37 +08:00
_tabBar = p.Q<TabBar>(TabPath);
if (_tabBar is not null)
{
break;
}
p = p.parent;
2024-11-03 16:42:23 +08:00
}
2024-12-30 21:34:37 +08:00
if (_tabBar is not null)
2024-12-28 23:19:55 +08:00
{
2024-12-30 21:34:37 +08:00
_tabBar.OnTabChanged += OnTabChanged;
_index = _tabBar.CurrentTab;
2024-12-28 23:19:55 +08:00
}
2024-11-03 16:42:23 +08:00
OnTabChanged(_index);
}
private void OnTabChanged(int obj)
{
_index = obj;
2024-12-30 21:34:37 +08:00
if (childCount < 0) return;
2024-11-03 16:42:23 +08:00
for (var i = 0; i < childCount; i++)
{
var visualElement = this[i];
visualElement.SetActive(i == _index);
}
}
}
}