Forest_Client/Forest/Assets/PhxhSDK/Phxh/UI/UIImageDropDown.cs

83 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
namespace PhxhSDK
{
public class UIImageDropDown<T> : UIGameObjectWrapper
{
private readonly Action<T> _onValueChanged;
private readonly TMP_Dropdown _dropdown;
private readonly Func<T, string> _data2Text;
private readonly Func<T, Sprite> _data2Img;
private readonly TMP_Text _text;
private int _currentSelected;
private List<T> _datas;
public UIImageDropDown(GameObject go, GameObject selectTextObject, Action<T> onValueChanged,
Func<T, string> data2Text,Func<T,Sprite>data2Img) : base(go, true)
{
_dropdown = GetItem<TMP_Dropdown>();
_text = GetItem<TMP_Text>(selectTextObject);
if (_dropdown == null)
{
DebugUtil.LogError("cannot find TMP_Dropdown component in {0}", go?.name);
}
if (_text == null)
{
DebugUtil.LogError("cannot find TMP_Text component in {0}", selectTextObject?.name);
}
_onValueChanged = onValueChanged;
_data2Img = data2Img;
_data2Text = data2Text;
_dropdown.onValueChanged.AddListener(_OnValueChanged);
}
public void SetData(IEnumerable<T> collection)
{
_datas?.Clear();
var enumerable = collection.ToList();
_datas = new List<T>(enumerable);
if (_dropdown != null)
{
_dropdown.ClearOptions();
foreach (var item in enumerable)
{
var data = new TMP_Dropdown.OptionData();
if (_data2Img != null)
{
data.image = _data2Img(item);
}
_dropdown.options.Add(data);
}
}
}
public void Clear()
{
_dropdown?.ClearOptions();
}
private void _OnValueChanged(int value)
{
_currentSelected = value;
if (_datas != null && _currentSelected >= 0 && _currentSelected < _datas.Count)
{
if (_data2Text != null && _text != null)
{
_text.text = _data2Text(_datas[_currentSelected]);
}
_onValueChanged?.Invoke(_datas[_currentSelected]);
}
}
}
}