0

I've an app in which I need to highlight words. It's like audio books which reads & highlight arabic text.

There are methods to highlight a particular sub-string from label but I don't want that. I want to something like. Lets consider following sentance.

"I am an iOS Developer & I work in BEE Technologies"

Now, what I want, I would say, highlight character number

1-1,   -> I
3-4,   -> am
6-7,   -> an
9-11,  ->iOS
13-21, ->Developer

Because I don't think there is any way to simply keep highlighting word by word till end of line.

AbaEesa
  • 998
  • 1
  • 6
  • 22
  • 2
    Check this http://stackoverflow.com/questions/25207373/changing-specific-texts-color-using-nsmutableattributedstring-in-swift you can achieve this by using `NSAttributedText` by determining NSRange. – iphonic Jan 16 '17 at 07:13

1 Answers1

4

This is a generic solution, it might be not the best one, but at least it works for me as it should...

I -almost- faced the same case, what I did to achieve it (consider that these are steps to do):

  • Creating an array of ranges: I calculated the ranges of each word and add them to an array to let it easier when determining which word (range) should be highlighted. For example, when you to highlight "I", you should highlight the range which is at 0 index and so on...

Here is an example of how you can generate an array of NSRange:

let myText = "I am an iOS Developer"

let arrayOfWords = myText.components(separatedBy: " ")

var currentLocation = 0
var currentLength = 0
var arrayOfRanges = [NSRange]()

for word in arrayOfWords {
    currentLength = word.characters.count
    arrayOfRanges.append(NSRange(location: currentLocation, length: currentLength))

    currentLocation += currentLength + 1
}

for rng in arrayOfRanges {
    print("location: \(rng.location) length: \(rng.length)")
}

/* output is:
 location: 0 length: 1
 location: 2 length: 2
 location: 5 length: 2
 location: 8 length: 3
 location: 12 length: 9
 */
  • Using Timer: to keep checking what is the current second (declare a variable cuurentSecond -for example- and increment it by 1 each second). Based on what is the current second, you can determine which word should be highlighted. For example: let's say that "I" should be highlighted between 0 and 1 second and "am" should be highlighted from 2 to 3 second, now you can check if the cuurentSecond between 0 and 1 to highlight "I", if it is between 2 and 3 to highlight "am" and so on...

  • Using NSMutableAttributedString: you should use it to do the actual highlighting for the words (ranges as mentioned int the first bullet). You can also check these questions/answers to know how to use it:

iOS - Highlight One Word Or Multiple Words In A UITextView.

How can I change style of some words in my UITextView one by one in Swift?

Hope this helped...

Community
  • 1
  • 1
Ahmad F
  • 30,560
  • 17
  • 97
  • 143