自定义 DropList dropdown

                                                        

一,前言

    unity自带的dropdown我一直觉得用着太费劲 调整不好调整的 灵活性太低为此我自定义了个droplist 如下:

二  原理讲解

   折叠状态:default   options隐藏

   首先需要做一个折叠时候的显示  图片 文字 选中框  具体可以自行diy  我这里图片是全铺于父物体 如此我们调整droplist大小即可实现调整 折叠状态显示内容

   down up 是右侧三角符号 用于展示当前是否打开下拉列表 入不需要可自行去掉

  Options  选项

   Droplist  是一个模板 是展开后的选项生成的模板 所以只需要做好这一个模板即可

    list 是用于排列下拉框的所以需要如下组件:

 

三  代码实现:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[Serializable]
public class OnClick : UnityEvent { }

public class DropList : MonoBehaviour {
    
    public GameObject optionsTr;//选项列表

    public GameObject currentChoose;//当前选项框

    public bool listShow = false;//列表是否已经打开
    public OnClick onshow,onhide;//点击事件
    public Sprite chooseIcon;//选择框

    public GameObject listItemPre;//选项预制体
    public Transform listGrid;//选项列表
    public Text defaultTex;
    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="names"></param>
    public void InitDropList(List<string> names)
    {
        for (int i = 0; i < names.Count; i++)
        {
            GameObject item = Instantiate(listItemPre, listGrid);
            int index = i;
            item.GetComponentInChildren<Button>().onClick.AddListener(() =>
            {
                if (currentChoose != null) currentChoose.SetActive(false);
                defaultTex.text = names[index];
                currentChoose = item.transform.GetChild(1).gameObject;
                currentChoose .SetActive(true);
                ShowList();
            });
            item.GetComponentInChildren<Text>().text = names[i];
            if(i == 0)
            {
                defaultTex.text = names[i];
                currentChoose = item.transform.GetChild(1).gameObject;
                currentChoose.SetActive(true);
            }
            item.SetActive(true);
        }
        optionsTr.SetActive(false);
        listGrid.GetComponent<VerticalLayoutGroup>().enabled = true;
    }

    /// <summary>
    /// 显示列表
    /// </summary>
    public void ShowList()
    {
        listShow = !listShow;
        if(listShow)
        {
            onshow.Invoke();
            optionsTr.SetActive(true);
        }
        else
        {
            onhide.Invoke();
            optionsTr.SetActive(false );
        }

    }
}

此外我增加了事件监听 可以在面板上添加 列表打开和关闭的额外事件

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值