2012-02-01 47 views
5

我想在所選範圍內替換UITextView文本中的文本。這是我的問題。我在這裏提到我做了什麼?我想做什麼?我有一個UITextView並在textview中輸入下面的文本。如何用所選範圍替換UITextView中的文本?

Ask question here,我在textview中保存了文本的範圍。文本範圍是{17, 0}。我在-(void) textViewDidChange:(UITextView *)textView代表中拿NSRange。

現在我想要替換文本questionanswer,我想替換文本herethem. The UITextView.text look like this,替換文本後問問他們`。

如何將所選範圍的文字替換?你能幫我麼?提前致謝。

回答

4

嗯......我不知道正確理解你想要做什麼,但如果你的目標是要改變一些字符選擇的範圍,你可以按照下列步驟操作:

讓您UITextView的內容並把它放在一個的NSString:該範圍內的字符,你想

NSString *textViewContent = textView.text; 

變化:

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

替換舊的內容與新的:

textView.text = newContent; 

無論如何,如果你只是想更換問的問題在這裏請回答最快的解決方法就是:

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]; 
8

自iOS 7以來,textView中的textStorage繼承自NSMutableAttributedString,因此您可以使用這些方法:

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

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

我一直在尋找通過很多答案,但是這是唯一一個幫助我避免自動滾動到頂部我每次在其更改文本時的TextView。完美的作品。 – nshuman 2015-01-07 14:02:20

相關問題