Unity-DropDown的搜索功能实现

1. 需要创建一个DropDown和inputFeild对象,UI的放置如下:(将inputFeild放置在dropdown的上方)

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


public class Test1: MonoBehaviour {

    public InputField inputText;//该输入框放置在DropDown处
    public Dropdown dropDownList;
    List<string> strList;
    List<Dropdown.OptionData> options = new List<Dropdown.OptionData>();//这是用来存Dropdown.OptionData的中间变量
    // Use this for initialization
    void Start () {
        //strList内的内容设置好后就不要再进行改动了
        strList = new List<string>();
        strList.Add("北京");
        strList.Add("上海");
        strList.Add("深圳");
        strList.Add("广州");
        strList.Add("内蒙古");
        strList.Add("蒙古大草原");
        options.Add(new Dropdown.OptionData("请选择所在地区"));
        foreach (string s in strList)
        {
            options.Add(new Dropdown.OptionData(s));

        }
        dropDownList.GetComponent<Dropdown>().options = options;
    }
    void Update()
    {
    }
    //这个函数放在inputFeild的OnEndEdit事件下
    public void onValueChange()
    {
        //使用LINQ进行查询
        var results = from temp in strList where (temp.Contains(inputText.text)) select temp;
            options.Clear();
            foreach (string s in results)
            {
                //Debug.Log(s);
                options.Add(new Dropdown.OptionData(s));
                dropDownList.GetComponent<Dropdown>().options = options;
            }
            dropDownList.Show();

    }
//这个函数放在DropDown的OnValueChange事件下
    public void DropDownOnValueChange()
    {
        inputText.text = dropDownList.transform.GetChild(0).GetComponent<Text>().text;
        options.Clear();
        foreach (string s in strList)
        {
            options.Add(new Dropdown.OptionData(s));

        }
        dropDownList.GetComponent<Dropdown>().options = options;

    }

}


猜你喜欢

转载自blog.csdn.net/star__119/article/details/79558524