using System;
using AlicizaX.UI.Extension;
using UnityEngine;
using UnityEngine.UI;
namespace AlicizaX.UI
{
///
/// 视图持有者基类,用于缓存和复用列表项视图
///
public abstract class ViewHolder : MonoBehaviour
{
private RectTransform rectTransform;
///
/// 获取 RectTransform 组件
///
public RectTransform RectTransform
{
get
{
if (rectTransform == null)
{
rectTransform = GetComponent();
}
return rectTransform;
}
private set { rectTransform = value; }
}
///
/// 视图名称,用于区分不同类型的视图
///
public string Name { get; internal set; }
///
/// 当前绑定的数据索引
///
public int Index { get; internal set; }
///
/// 选中状态
///
public bool ChoiseState { private set; get; }
///
/// 获取视图的尺寸
///
public Vector2 SizeDelta => RectTransform.sizeDelta;
private IButton _button;
///
/// 视图首次创建时调用
///
protected internal virtual void OnStart()
{
}
///
/// 视图被回收到对象池时调用
///
protected internal virtual void OnRecycled()
{
}
///
/// 绑定视图数据(抽象方法,子类必须实现)
///
/// 数据类型
/// 要绑定的数据
public abstract void BindViewData(T data);
///
/// 绑定列表项点击事件
///
/// 数据类型
/// 数据对象
/// 点击回调
protected internal virtual void BindItemClick(T data, Action action)
{
if (_button is null && !TryGetComponent(out _button))
{
Log.Warning("找不到Button组件");
return;
}
_button.onClick.RemoveAllListeners();
_button.onClick.AddListener(() => action?.Invoke(data));
}
///
/// 绑定选中状态
///
/// 是否选中
protected internal void BindChoiceState(bool state)
{
if (ChoiseState != state)
{
ChoiseState = state;
OnBindChoiceState(state);
}
}
///
/// 选中状态改变时的回调(可在子类中重写)
///
/// 是否选中
protected internal virtual void OnBindChoiceState(bool state)
{
}
}
}