如何在UITextView中用所选范围替换文本?

7
我想替换UITextView的选定范围内的文本。这是我的问题。下面我会提到我做了什么和我想做什么。我有一个UITextView,并在textview中输入了以下文本。
“提问”,我已经保存了textview文本中的范围。文本范围为{17,0}。我在-(void)textViewDidChange:(UITextView *)textView代理中获取NSRange。
现在我想用“答案”替换“问题”,用“它们”替换“这里”。替换后,UITextView的文本如下:“问答它们”。
我该如何使用所选范围替换文本?你能帮我吗?先感谢您。
3个回答

16

iOS 7 以后,textView 中有一个继承自 NSMutableAttributedString 的 textStorage,因此您可以使用这些方法:

Objective-C

[self.textView.textStorage replaceCharactersInRange:withString:];
或者
[self.textView.textStorage replaceCharactersInRange:withAttributedString:];

Swift

textView.textStorage.replaceCharacters(in: range, with: string)

我查看了许多答案,但只有这个答案帮助我避免textView在每次更改文本时自动滚动到顶部。完美地运作。 - 0xNSHuman

4

好的...我不确定我是否正确理解了你想要做什么,但如果你的目标是在所选范围内更改一些字符,你可以按照以下步骤进行:

获取你的UITextView内容并将其放入NSString中:

NSString *textViewContent = textView.text;

更改您想要的范围内的字符:

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

用新内容替换旧内容:

textView.text = newContent;

无论如何,如果你只是想用Ask answer them替换Ask question here,最快的解决办法就是:
textView.text = @"Ask answer them";

0

从我头脑中想到的好的解决方案...

NSArray *Dividedstring = [[self.TextView.text] componentsSeparatedByString:@" question here "]; // this will divide the string into two parts ..one before question here and second after question here.
NSString  * firstpart = [Dividedstring objectAtIndex:0]; 
NSString  * secondpart = [Dividedstring objectAtIndex:0];

self.TextView.text = [NSString stringwithFormat:@"%@ answer here %@",firstpart,secondpart];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接