myCodeStudio
22Dec/097

UITextView Scrolling

After hours of fiddling (and cursing) with the UITextView scrolling behavior, I finally got the behavior I wanted. If you ever need to programmatically insert text into a UITextView and move the cursor to right after the insertion point, the following code snippet should work. Make sure you do the bolded items otherwise the UITextView won't scroll properly.

textview.scrollEnabled = NO;
NSString *contentsToAdd = @"some string";
NSInteger len = [contentsToAdd length];
NSRange cursorPosition = [self.textview selectedRange];
NSMutableString *tfContent = [[NSMutableString alloc] initWithString:[self.textview text]];

// insert the string or replace the selection
NSUInteger loc = cursorPosition.location;
if (cursorPosition.length == 0)
  [tfContent insertString:contentsToAdd atIndex:loc];
else
  [tfContent replaceCharactersInRange:cursorPosition withString:contentsToAdd];

// now update the text view
[self.text setText:tfContent];
cursorPosition.location = loc + len;
cursorPosition.length = 0;

// should move the cursor
textview.scrollEnabled = YES;
self.textview.selectedRange = cursorPosition;
[tf release];

About Gary

No description. Please complete your profile.
Comments (7) Trackbacks (0)
  1. I placed this code in the textViewShouldBeginEditing delegate but the cursor position always comes back to the end of the string.

    Is this the right place for the code?

    Thanks,
    SV

  2. I actually had this code from a button press as I was inserting text at the cursor based on what button was pressed. My text view was already in edit mode. What’s the behavior you are looking for? Is your text view already in edit mode and some operation causes you to replace the text in the text view?

  3. It was useful for me. Thanks a lot

  4. Appreciate it a whole lot!! Was stuck on this and I was extremely grateful to find this online! Thanks :)

  5. I’m glad it helped!

  6. Does the default undo feature still work when you use this method?

  7. I’m not sure – I haven’t tried that. If you have let me know! Thanks.


Leave a comment


No trackbacks yet.