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];
January 3rd, 2010 - 11:51
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
January 3rd, 2010 - 14:04
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?
February 27th, 2010 - 01:00
It was useful for me. Thanks a lot
April 20th, 2010 - 15:27
Appreciate it a whole lot!! Was stuck on this and I was extremely grateful to find this online! Thanks
April 22nd, 2010 - 01:49
I’m glad it helped!
May 6th, 2010 - 12:21
Does the default undo feature still work when you use this method?
May 6th, 2010 - 21:10
I’m not sure – I haven’t tried that. If you have let me know! Thanks.