0

I have an iOS Swift 2/Xcode 7 project that searches a string and identifies substrings from a specified list. The input string will change, but the substrings remain the same.

Something like this inputString "SALT, WATER, FLOUR"

Comparison substrings "SALT, PEPPER"

Since "SALT" is present, it would become highlighted to look like this

SALT WATER FLOUR

and ideally in a different color - so Red for "SALT", Green for "PEPPER", anything else would be black.

Here is the basic code for searching for the substrings -

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")
                        }
                    }

The iList is displayed in a TextView.

The desired result would look something like

SALT, FLOUR, WATER....

The examples I found relied on being able to change text colors at specific positions within the string. In this case, the location of a substring (if present) will vary for every use.

Help with this would be greatly appreciated. Thank you.

CM.
  • 519
  • 5
  • 19

1 Answers1

0

You need to use NSAttributedString for this purpose. Check out this post: http://ramezanpour.net/post/2014/01/28/customize-your-texts-in-ios-using-nsattributedstring/

Use substringWithRange method to find the range of the string that you need to make bold or change color and then use the returned range as shown in the tutorial.

Ankit Goel
  • 6,257
  • 4
  • 36
  • 48