Take the 2-minute tour ×


this is the thing: i'm trying to simulate a key press with an button: I have an UITextView, the user can enter text as usual and, touching a button... it would have to appear let's say "b" in the current cursor position.

It doesn't appear to be very hard but googling i found nothing at all.

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

You can set manually the text in the UITextView in the button event method:

UITextView* yourTextView;

NSRange selectedRange = yourTextView.selectedRange;

NSString* currentText = yourTextView.text;

NSString* yourString = @"b"; // Or any other string of any length

// Insert the string at the cursor selected range
NSString* modifiedText = [currentText substringToIndex: range.location];
modifiedText = [modifiedText stringByAppendingFormat:@"%@%@", yourString,
    [currentText substringFromIndex: range.location + range.length]];

// Replace the text of the UITextView
yourTextView.text = modifiedText;

Edited to insert the string at the cursor position. With this modification, if you select text and hit the button, you will replace what you have selected.

Edit: Fixed compilation issues

Hope it helps.


share|improve this answer
As a matter of fact, i'm at work right now and i don't have here with me the project i was working on, as soon as i got home i'll give your code a try, it seems it might work :) Thanks! –  ferostar Mar 9 '11 at 18:37
Done! It worked beautifully, with two things: selectedRange is not a pointer and instead of concatenating with "+" (impossible in obj-c) i did it with stringByAppendingFormat. –  ferostar Mar 10 '11 at 1:46
@seretur: Good to know. I fixed the issues that you mentioned. Regards! –  redent84 Mar 10 '11 at 9:41
add comment

Your Answer


