UI框架主要实现压栈和出栈的操作,实现页面之间关系的管理由于我们打开的页面有如下几种情况
- 置顶
- 弹窗
- 正常页面
- 最底部
所以我们需要建立一个类型,好让管理器知道页面的展现方式
public enum EUIOpenType
{
Background = 0,
Default = 10,
Popup = 20,
Top = 30
}
所有页面类型继承页面基类
public abstract class UIPanel : MonoBehaviour
{
public EUIOpenType Type { get; set; }
public abstract void Init(params object[] args);
public abstract void OnShow();
public virtual void OnPause() { }
public virtual void OnResume() { }
public virtual void BindData() { }
public virtual void UnBindData() { }
public virtual void OnDataBindingUpdate() { }
public virtual void OnClicked() { }
public virtual void OnExit() { }
}
主体的UIManager
public class UIManager : MonoSingleton<UIManager>
{
private Stack<UIPanel> stack;
private Dictionary<string, UIPanel> uiPool = new();
protected override void Init()
{
stack = new Stack<UIPanel>();
}
#region Public Function
public void OpenPanel(string name, params object[] args)
{
OpenPanel(name, EUIOpenType.Default, args);
}
public void OpenPanel(string name, EUIOpenType type, params object[] args)
{
//停止上一个界面
if (stack.Count > 0)
{
UIPanel curPanel = stack.Peek();
curPanel.OnPause();
}
PushPanel(name, type, args);
}
public void ClosePanel()
{
if (stack.Count <= 0)
{
return;
}
UIPanel top = stack.Pop();
top.OnExit();
if (stack.Count > 0)
{
UIPanel panel = stack.Peek();
panel.OnResume();
}
}
public void ReplacePanel(string name, params object[] args)
{
EUIOpenType type = EUIOpenType.Default;
if (stack.Count > 0)
{
UIPanel curPanel = stack.Pop();
type = curPanel.Type;
curPanel.OnExit();
}
PushPanel(name, type, args);
}
public UIPanel GetCurrentPanel()
{
if (stack.Count > 0)
return stack.Peek();
else
return null;
}
#endregion
#region Private Function
private void PushPanel(string name, EUIOpenType type, params object[] args)
{
name = name.ToLower();
if (uiPool.ContainsKey(name))
{
ShowPanel(name, type, args);
}
else
{
GameResManager.Ins.LoadUI(name, (go) =>
{
GameObject goPanel = Instantiate(go as GameObject, transform);
UIPanel panel = goPanel.GetComponent<UIPanel>();
uiPool[name] = panel;
ShowPanel(name);
});
}
}
private void ShowPanel(string name, EUIOpenType type = EUIOpenType.Default, params object[] args)
{
var panel = uiPool[name];
panel.Type = type;
panel.Init(args);
stack.Push(panel);
panel.OnShow();
}
#endregion
protected override void Release()
{
foreach (var item in uiPool)
{
item.Value.OnExit();
Destroy(item.Value.gameObject);
}
uiPool.Clear();
}
}