【问题标题】:Change substring color within dynamic string [duplicate]更改动态字符串中的子字符串颜色[重复]
【发布时间】:2016-01-02 21:51:27
【问题描述】:

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

类似的东西 inputString "盐、水、面粉"

比较子字符串“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 中。

期望的结果看起来像

、面粉、水......

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

我们将不胜感激。 谢谢。

【问题讨论】:

    标签: ios string swift


    【解决方案1】:

    为此,您需要使用 NSAttributedString。 看看这个帖子: http://ramezanpour.net/post/2014/01/28/customize-your-texts-in-ios-using-nsattributedstring/

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

    【讨论】:

      猜你喜欢
      • 2012-04-13
      • 2012-06-15
      • 2013-03-30
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      相关资源
      最近更新 更多