Kiran Kumar
Kiran Kumar

Reputation: 677

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.

Upvotes: 3

Views: 1171

Answers (3)

Thomas Deniau
Thomas Deniau

Reputation: 2573

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.

Upvotes: 2

Kiran Kumar
Kiran Kumar

Reputation: 677

I wrote the code like this. I am new to the IOS so if i am wrong kindly correct me.

  • (NSMutableDictionary *)attDict {

    if (!_attDict) { _attDict = [NSMutableDictionary dictionary];

    UIFont *font = [UIFont systemFontOfSize:self.fontSize];
    // UIFont *font = [UIFont fontWithName:@"TimesNewRomanPSMT" size:self.fontSize];
     [_attDict setObject:font forKey:NSFontAttributeName];
    [_attDict setObject:[UIColor blueColor] forKey:NSForegroundColorAttributeName];
    

    } return _attDict; }

    [[displayingArticleView contentView].textStorage setAttributes:self.attDict range:theRange] ;

Thanks

Upvotes: 2

Alex Andrews
Alex Andrews

Reputation: 1498

If you just want to replace any text in your UITextField with some other on the fly, You can use the string replacement method, Like

[textField.text stringByReplacingOccurrencesOfString:@"your string" withString:@"string to be replaced"];

This will Replace all occurrences of the target(string to be replaced) string with replacement.

Upvotes: 0

Related Questions