gpt4 book ai didi

ios - 更改动态字符串中的子字符串颜色

转载 作者:行者123 更新时间:2023-11-30 13:48:54 24 4
gpt4 key购买 nike

我有一个 iOS Swift 2/Xcode 7 项目,用于搜索字符串并从指定列表中识别子字符串。输入字符串会改变,但子字符串保持不变。

类似这样的事情输入字符串“盐、水、面粉”

比较子字符串“SALT, PEPPER”

由于“SALT”存在,它会突出显示,如下所示

水面粉

最好是不同的颜色 - 所以红色代表“盐”,绿色代表“胡椒”,其他任何颜色都是黑色。

这是搜索子字符串的基本代码 -

iList = "SALT, FLOUR, WATER...."  //actually pulled from CORE data, different for every search

for ingredient in ["SALT", "PEPPER", "SUGAR"] {
if iList.rangeOfString(ingredient) != nil {
print("Ingredient Found \(ingredient) found")
}
}

iList 显示在 TextView 中。

期望的结果看起来像这样

、面粉、水......

我发现的示例依赖于能够更改字符串中特定位置的文本颜色。在这种情况下,子字符串(如果存在)的位置每次使用都会有所不同。

对此提供帮助将不胜感激。谢谢。

最佳答案

您需要使用 NSAttributedString 来实现此目的。查看这篇文章: http://ramezanpour.net/post/2014/01/28/customize-your-texts-in-ios-using-nsattributedstring/

使用 substringWithRange 方法查找需要加粗或更改颜色的字符串的范围,然后使用返回的范围,如教程中所示。

关于ios - 更改动态字符串中的子字符串颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34571091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com