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

时间:2016-01-02 21:51:27

标签: ios string swift

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

像这样的东西 inputString“SALT,WATER,FLOUR”

比较子串“SALT,PEPPER”

由于存在“SALT”,它将突出显示为这样

水面粉

理想情况下颜色不同 - 红色为“SALT”,绿色为“PEPPER”,其他任何颜色都是黑色。

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

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中。

期望的结果看起来像

SALT ,面粉,水......

我发现的例子依赖于能够在字符串中的特定位置更改文本颜色。在这种情况下,子串(如果存在)的位置将因每次使用而异。

非常感谢帮助。 谢谢。

1 个答案:

答案 0 :(得分:0)

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

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