96 lines
2.8 KiB
C#
96 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
|
|
namespace PhxhSDK
|
|
{
|
|
/// <summary>
|
|
/// 文本下拉框
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public class UITextDropdown<T> : UIGameObjectWrapper
|
|
{
|
|
/// <summary>
|
|
/// 选中变化回调
|
|
/// </summary>
|
|
private readonly Action<T> onValueChanged;
|
|
/// <summary>
|
|
/// 下拉框
|
|
/// </summary>
|
|
private readonly TMP_Dropdown dropdown;
|
|
private readonly Func<T, string> data2Text;
|
|
private readonly TMP_Text text;
|
|
private int currentSelected;
|
|
private List<T> listData;
|
|
|
|
public UITextDropdown(GameObject root,
|
|
GameObject selectTextObject,
|
|
Action<T> onValueChanged,
|
|
Func<T, string> data2Text) : base(root, true)
|
|
{
|
|
dropdown = GetItem<TMP_Dropdown>();
|
|
text = GetItem<TMP_Text>(selectTextObject);
|
|
|
|
if (dropdown == null)
|
|
DebugUtil.LogError($"cannot find TMP_Dropdown component in {(root == null ? null : root.name)}");
|
|
|
|
if (text == null)
|
|
DebugUtil.LogError($"cannot find TMP_Text component in {(selectTextObject == null ? null : selectTextObject.name)}");
|
|
|
|
this.onValueChanged = onValueChanged;
|
|
this.data2Text = data2Text;
|
|
|
|
dropdown.onValueChanged.AddListener(OnValueChanged);
|
|
}
|
|
|
|
public void SetData(IEnumerable<T> collection)
|
|
{
|
|
listData ??= new(collection.Count());
|
|
listData.Clear();
|
|
listData.AddRange(collection);
|
|
|
|
if (dropdown == null)
|
|
return;
|
|
|
|
dropdown.ClearOptions();
|
|
foreach (T item in listData)
|
|
{
|
|
TMP_Dropdown.OptionData data = new();
|
|
if (data2Text != null)
|
|
data.text = data2Text(item);
|
|
|
|
dropdown.options.Add(data);
|
|
}
|
|
|
|
if (listData != null && currentSelected >= 0 && currentSelected < listData.Count)
|
|
{
|
|
if (data2Text != null && text != null)
|
|
text.text = data2Text(listData[currentSelected]);
|
|
}
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
dropdown?.ClearOptions();
|
|
}
|
|
public void SetValue(int value)
|
|
{
|
|
currentSelected = value;
|
|
}
|
|
|
|
private void OnValueChanged(int value)
|
|
{
|
|
currentSelected = value;
|
|
|
|
if (listData != null && currentSelected >= 0 && currentSelected < listData.Count)
|
|
{
|
|
if (data2Text != null && text != null)
|
|
text.text = data2Text(listData[currentSelected]);
|
|
|
|
onValueChanged?.Invoke(listData[currentSelected]);
|
|
}
|
|
}
|
|
}
|
|
} |