【问题标题】:How to display list in gui in runtime如何在运行时在 gui 中显示列表
【发布时间】:2017-04-06 18:28:17
【问题描述】:

我正在尝试创建一个类似于 Facebook 的搜索界面。也就是说,您输入全部或部分名称,匹配项将显示在下面的列表中。

我知道如何从 InputField (SearchBar) 中提取输入,但我不知道如何在运行时在下面的面板中显示匹配结果。

为每个匹配项创建一个新标签/按钮并附加到...面板? 我应该使用什么容器? 我如何真正“添加/追加”?

任何帮助将不胜感激。

这是我的场景:

这是我的代码:

using UnityEngine;
using UnityEngine.UI;
using System;

public class SearchScript : MonoBehaviour {

    public InputField SearchBar;
    public GameObject Panel;
    public List<String> myList;

    public void Start() {

        myList = new List <String>();
        myList.Add("Andre");
        myList.Add("Angela");
        myList.Add("Temi");
        myList.Add("Tupac");
        myList.Add("Graham");
        myList.Add("Grandpa");
        myList.Add("Michael");
        myList.Add("Miguel");

        SearchBar.onValueChanged.AddListener(delegate {ValueChangeCheck(myList); });
    }

    public void ValueChangeCheck(List<string> myList) {

        string contents = SearchBar.text;

        List<String> outList = new List <String> ();

        for (int i = 0; i < myList.Count; i++) {
            if (myList [i].Contains (contents)) {
                outList.Add (myList [i]);
            }
        }

        for (int i = 0; i < outList.Count; i++) {
            >>HELP<<
        }
    }
}

【问题讨论】:

    标签: c# user-interface unity3d


    【解决方案1】:

    Unity 手册中的This page 概括地描述了您需要执行的操作。您要做的第一件事是(在编辑器中)制作一个空白按钮/标签或任何您希望最终产品看起来的东西。对于这个例子,我将把它当作一个按钮。一旦你的按钮看起来像你想要的那样,将位置设置为 (0,0) 并使其成为预制件。在 MonoBehaviour 中创建一个公共字段,然后在编辑器中将预制件拖入其中。看起来像这样:

    public GameObject ButtonPrefab;
    

    接下来,在您的循环中,您需要实例化每个按钮,确保将新对象作为您的画布的父对象(这是您的 SearchBar 的父对象,因此我们有一个简单的方法来获取它)。然后分配您的文本并将其向下移动,您将获得成功!

    for (int i = 0; i < outList.Count; i++) {
        var newButton = Instantiate(ButtonPrefab,SearchBar.transform.parent,false) as GameObject;
    
        // This assumes you have a Text component  in your prefab
        newButton.GetComponent<Text>().text = outList[i];  
    
        // You'll just have to experiment to find the value that works for you here
        newButton.transform.position += Vector2.down * 20 * (i + 1); 
    }
    

    【讨论】:

    • 天哪,这非常有用。如果我可能会问,您会如何建议在更改搜索栏条目时销毁按钮?
    • 将按钮添加到循环中的 List&lt;GameObject&gt; 中,您可以将其保存到某个地方的对象中,可能是一个私有字段。稍后当您想销毁按钮时,遍历列表,销毁其中的每个按钮,然后 .Clear() 列表
    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    相关资源
    最近更新 更多