Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert text at any cursor position in uitextview?

i want to implement Code by which i can start to insert text at any position of cursor in UITextView in iphone sdk

any idea? thank you in advance..

i refereed this link: iPhone SDK: How to create a UITextView that inserts text where you tap?

But not Getting it.

like image 906
kushalrshah Avatar asked Jan 13 '12 06:01

kushalrshah


2 Answers

Dan's answer is manually changing the text. It's not playing well with UITextView's UndoManager.

Actually it's very easy to insert text with UITextInput protocol API, which is supported by UITextView and UITextField.

[textView replaceRange:textView.selectedTextRange withText:insertingString];

Note: It's selectedTextRange in UITextInput protocol, rather than selectedRange

like image 148
ethanhuang13 Avatar answered Oct 12 '22 09:10

ethanhuang13


This is what I use with a custom keyboard, seems to work ok, there may be a cleaner approach, not sure.

NSRange range = myTextView.selectedRange;  
NSString * firstHalfString = [myTextView.text substringToIndex:range.location];  
NSString * secondHalfString = [myTextView.text substringFromIndex: range.location];  
myTextView.scrollEnabled = NO;  // turn off scrolling  

NSString * insertingString = [NSString stringWithFormat:@"your string value here"];

myTextView.text = [NSString stringWithFormat: @"%@%@%@",  
                 firstHalfString,  
                 insertingString,  
                 secondHalfString];  
range.location += [insertingString length];  
myTextView.selectedRange = range;  
myTextView.scrollEnabled = YES;  // turn scrolling back on.
like image 30
Dan Avatar answered Oct 12 '22 09:10

Dan