如何搜索和突出显示按钮文本中的子字符串?(C#)
我想尝试在按钮数组中搜索特定字符串。。。如果找到该字符串,是否可以突出显示其中的子字符串(粗体/下划线/更改文本颜色)?我已经得到了下面的代码,但它改变了按钮内整个文本的字体颜色如何搜索和突出显示按钮文本中的子字符串?(C#),c#,arrays,string,user-interface,unity3d,C#,Arrays,String,User Interface,Unity3d,我想尝试在按钮数组中搜索特定字符串。。。如果找到该字符串,是否可以突出显示其中的子字符串(粗体/下划线/更改文本颜色)?我已经得到了下面的代码,但它改变了按钮内整个文本的字体颜色 按钮[i].getComponentChildren().color=color.red 下面是我尝试做的一个例子: 我有一个3个按钮的数组,分别有文本bench、bend和bend。我想在这些字符串中搜索子字符串ben。如果找到了,我想改变单词中的子字符串的文本颜色 在文本组件本身上启用 然后可以使用颜色标记将部分文
按钮[i].getComponentChildren().color=color.red代码>
下面是我尝试做的一个例子:
我有一个3个按钮的数组,分别有文本bench
、bend
和bend
。我想在这些字符串中搜索子字符串ben
。如果找到了,我想改变单词中的子字符串的文本颜色 在文本组件本身上启用
然后可以使用颜色标记将部分文本换行,如下所示:
有益的
在代码方面,您只需首先获取当前文本(并删除任何标记),然后替换该单词的所有匹配项,使其与完全相同的单词匹配,但在其周围有一个包装器,如下所示:
[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;
}
[序列化字段]
专用文本targetText;
void Start()
{
//确保此文本可以支持富文本。
//(或在inspector中自己启用。)
targetText.supportRichText=true;
WrapMatchingWordInRed(“受益”);
}
public void WrapMatchingWordInRed(字符串字匹配){
//将从文本中删除任何与颜色相关的标记表达式。
var currText=Regex.Replace(targetText.text,”,string.Empty);
//将红色应用于匹配的单词。
字符串textWithMarkdown=currText.Replace(wordToMatch,“+wordToMatch+”);
targetText.text=带有标记的文本;
}
它将如下所示:
非常感谢您的帮助。通过数组访问按钮,我是否可以做到这一点:buttons[I].getComponentChildren().text
@Lloyd是的,只需修改我创建的函数,使其适用于按钮中的所有文本。只要它是一个文本,并且你已经在上面启用了RichText,它就会工作。这真是太神奇了!我会在早上实施的!非常感谢。我刚刚把你的答案标记为解决方案!非常感谢你!我真的很想在课文下面划线。。。看起来很傻,你不能只使用标签(