Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace text in UITextView with selected range?

I want to replace the text in UITextView text in selected range. This is my question. Here i mention what i did? and what i want to do?. I have an UITextView and entered the below text in textview.

Ask question here, i have saved the range in of the text in textview. The text range is {17, 0}. I take the NSRange in -(void) textViewDidChange:(UITextView *)textView delegate.

Now i want to replace the text question with answer and i want to replace the text here with them. The UITextView.text look like this,Ask answer them` after replaced the texts.

How can i replace the texts with the selected ranges? Can you please help me? Thanks in advance.

like image 281
Yuvaraj.M Avatar asked Feb 01 '12 13:02

Yuvaraj.M


2 Answers

Since iOS 7 there is the textStorage in the textView that inherits from NSMutableAttributedString so you can use those methods:

Objective-C

[self.textView.textStorage replaceCharactersInRange:withString:];

or

[self.textView.textStorage replaceCharactersInRange:withAttributedString:];

Swift

textView.textStorage.replaceCharacters(in: range, with: string)
like image 198
kschaeffler Avatar answered Oct 22 '22 09:10

kschaeffler


Well... I'm not sure to understand correctly what you're trying to do, but if your goal is to change some characters in a selected range you can follow these steps:

Get your UITextView content and put it in a NSString:

NSString *textViewContent = textView.text;

Change the characters in the range you want:

NSString *newContent = [textViewContent stringByReplacingCharactersInRange:range withString:replacement];

Replace old content with new one:

textView.text = newContent;

Anyway if you just want to replace Ask question here with Ask answer them the fastest solution is just:

textView.text = @"Ask answer them";
like image 20
Giuseppe Garassino Avatar answered Oct 22 '22 11:10

Giuseppe Garassino