Search code examples
iosobjective-cuitextviewtext-to-speech

Update the UITextView content dynamically in a specific range


I need to update the words dynamically in UiTextView content while TTS is playing without refresh the page.

Problem: While tts playing for the each word delegate(willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance) is calling. so at that time i am updating the text color using NSMutableAttributedString.

In this process the content in the textview is unstable because for each word page is refreshing.

so i need to update the text in textview without refreshing the page.

I wrote the code like this.

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:_theContent ];

[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:self.fontSize] range:[self wholeArticleRange]];

[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:theRange];

textview.attributedText = attrStr;

--In android we used spannable class to do this way. Is there any class in IOS like this?

Kindly give us solution ASAP

Thanks in advance.


Solution

  • You can access the text view's textStorage property, of type NSTextStorage, which is a subclass of NSMutableString. From there you can use any NSMutableString operation, including setting attributes on the various ranges, without sending an entirely new string to the text view (which will make it flicker).

    Do not forget to call beginEditing and endEditing to group edits together if you have to make multiple calls, in order to improve performance.