【问题标题】:How to search and highlight a substring within button text? (C#)如何在按钮文本中搜索和突出显示子字符串? (C#)
【发布时间】:2019-12-19 08:28:59
【问题描述】:

我想尝试在按钮数组中搜索特定字符串...如果找到该字符串,是否可以突出显示(粗体/下划线/更改文本颜色)其中的子字符串?我已经得到了下面的代码,但是它改变了按钮内整个文本的字体颜色.....

buttons[i].GetComponentInChildren<Text>().color = Color.red;

这是我正在尝试做的一个示例:

我有一组 3 个按钮,分别带有文本 benchbendbeneficial。我想在这些字符串中搜索子字符串ben。如果找到它,我想更改单词中该子字符串的文本颜色。

【问题讨论】:

    标签: c# arrays string user-interface unity3d


    【解决方案1】:

    在 Text 组件本身上启用 RichText

    然后,您可以像这样用颜色标记包裹部分文本:
    <color=red>ben</color>eficial

    在代码方面,您只需要先获取当前文本(并删除任何降价),然后替换所有出现的单词以匹配完全相同的单词,但围绕它进行包装,如下所示:

    [SerializeField]
    private Text targetText;
    
    void Start()
    {
        // Ensures that this text can support rich text.
        // (Or enable it yourself in the inspector.)
        targetText.supportRichText = true;
        WrapMatchingWordInRed("benef");
    }
    
    public void WrapMatchingWordInRed(string wordToMatch) {
        // Will remove any color-related markdown expression from your text.
        var currText = Regex.Replace(targetText.text, "<.*?>", string.Empty);
    
        // Apply red-color to words that matches.
        string textWithMarkdown = currText.Replace(wordToMatch, "<color=red>" + wordToMatch + "</color>");
    
        targetText.text = textWithMarkdown;
    }
    

    看起来像这样:

    【讨论】:

    • 非常感谢您的帮助。我可以通过数组访问按钮来做到这一点吗:buttons[i].GetComponentInChildren&lt;Text&gt;().text
    • @Lloyd 是的,只需稍微修改我所做的功能,使其适用于按钮中的所有文本。只要它是文本,它就可以工作,并且您在其上启用了富文本。
    • 这太棒了!将在早上实施!谢谢!
    • 我刚刚将您的答案标记为解决方案!太感谢了!不过,我真的很想在文本下划线……您不能只使用 标签似乎很愚蠢! :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多