先来两个效果展示图
由于Unity没有一个组件直接支持这个效果,所以以上效果是用两个组件通过一些小技巧结合拼起来的。
使用工具:Unity2018.2.18f1
使用组件:
1.UGUI --- Dropdown(下拉框)
2.UGUI --- InputField(输入框)
看下UI布局:
废话不多说直接干货上代码,此脚本挂在SearchBar上。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class SearchBar : MonoBehaviour
{
private Dropdown My_dorpdown
{
get
{
return transform.Find("Dropdown").gameObject.GetComponent<Dropdown>();
}
}
private InputField My_inputField
{
get
{
return transform.Find("InputField").gameObject.GetComponent<InputField>();
}
}
private void HideInputField()
{
My_inputField.GetComponent<Image>().color = new Color(1, 1, 1, 0);
My_inputField.placeholder.gameObject.SetActive(false);
My_inputField.textComponent.gameObject.SetActive(false);
}
private void ShowInputField()
{
My_inputField.GetComponent<Image>().color = new Color(1, 1, 1, 1);
My_inputField.placeholder.gameObject.SetActive(true);
My_inputField.textComponent.gameObject.SetActive(true);
}
public void SetPlaceholder(string _text)
{
My_inputField.placeholder.GetComponent<Text>().text = _text;
}
public List<string> LibraryList = new List<string>();
public void SetLibraryList(List<string> _list)
{
LibraryList = _list;
}
private List<string> ResultList = new List<string>();
private void Start()
{
Init();
My_dorpdown.onValueChanged.AddListener(delegate
{
My_inputField.text = My_dorpdown.transform.Find("Label").GetComponent<Text>().text;
HideInputField();
});
My_inputField.onEndEdit.AddListener(delegate
{
Filter();
ShowResult();
});
}
private void Init()
{
LibraryList.ForEach(i => ResultList.Add(i));
SetPlaceholder("请输入...");
}
private void Update()
{
if (My_inputField.isFocused && My_inputField.placeholder.gameObject.activeSelf == false)
{
ShowInputField();
}
}
//筛选字符
private void Filter()
{
ResultList = TextLenovo(My_inputField.textComponent.text, LibraryList);
}
private void ShowResult()
{
My_dorpdown.ClearOptions();
My_dorpdown.AddOptions(ResultList);
if (ResultList.Count != 0)
{
My_dorpdown.Show();
}
}
}
文本联想:
/// <summary>
/// 文本联想
/// </summary>
/// <param 传入的字符="text_item"></param>
/// <param 库数组="TextLibraryList"></param>
/// <param 返回结果数组="temp_list"></param>
/// <returns></returns>
public List<string> TextLenovo(string text_item, List<string> TextLibraryList)
{
List<string> temp_list = new List<string>();
foreach (string item in TextLibraryList)
{
if (item.Contains(text_item))
{
temp_list.Add(item);
}
}
return temp_list;
}