how to insert text at any cursor position in uitextview?
Asked Answered
A

4

17

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.

Adaptive answered 13/1, 2012 at 6:25 Comment(1)
Please Reply if any one had try before. I am also Doing the same but not getting success so please help.Postnasal
U
31

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

Unaunabated answered 26/3, 2014 at 23:46 Comment(0)
E
11

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.
Exurb answered 18/1, 2012 at 20:25 Comment(1)
thanx it is very intersting i have used it by deleting word where cursor is placed in textview by my custom keyboard:) thanx againSolberg
G
7

Here is the Glorfindel's answer in Swift3. The text its inserting here it pulls out of the clipboard.

if let textRange = myTextView.selectedTextRange {
   myTextView.replace(textRange, withText:UIPasteboard.general.string!)
}
Gatewood answered 1/4, 2017 at 18:53 Comment(0)
S
5

The simplest way (but it won't replace selected text) is to use the insertText: method:

[textView insertText:@"some text you want to insert"];

UITextView conforms to UITextInput which itself conforms to UIKeyInput.

Substantive answered 9/9, 2016 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.