8
votes

I have a view which is similar to the notes app - i.e. typing on a lined piece of paper. To make the text and the paper scroll simultaneously, I have disabled the UITextView's scrolling, and instead placed both my UITextView and my UIImageView inside a UIScrollView.

The only problem with this is that, when the user types, the text disappears below the keyboard, because obviously the UIScrollView does not know to scroll to the cursor position.

Is there any simple way I can retrieve the cursor position and tell the UIScrollView to scroll there?

---EDIT---

Starting from something similar here (where someone was trying to do something similar with a UITableView), I have managed to make a growing, editable UITextView with a fixed background that almost scrolls perfectly. The only issues now are:

  1. There is a slight judder as the text moves up if the user types particularly fast.
  2. If the user hides the keyboard, selects text at the bottom of the screen, and then shows the keyboard again, they have to type a couple of letters before the text becomes visible again - it doesn't scroll up immediately.
  3. When the user hides the keyboard, the animation as the scroll view's frame fills the screen doesn't feel quite right somehow.

Here is the code - I'd be really grateful if anyone can refine it further...

#import "NoteEditViewController.h"
#import "RLWideLabelTableCell.h"

@implementation NoteEditViewController
@synthesize keyboardSize;
@synthesize keyboardHideDuration;
@synthesize scrollView;
@synthesize noteTextView;

//
// Dealloc and all that stuff
//
- (void)loadView
{
    [super loadView];
    UIScrollView *aScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView = aScrollView; [aScrollView release];
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, noteTextView.frame.size.height);
    [self.view addSubview:scrollView];
}

- (void)viewDidLoad
{   
    [super viewDidLoad];

    // Get notified when keyboard is shown. Don't need notification when hidden because we are
    // using textViewDidEndEditing so we can start animating before the keyboard disappears.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];

    // Add the Done button so we can test dismissal of the keyboard    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
        target:self
        action:@selector(doneButton:)];
    self.navigationItem.rightBarButtonItem = doneButton; [doneButton release];

    // Add the background image that will scroll with the text
    CGRect noteImageFrame = CGRectMake(self.view.bounds.origin.x, 
                                       noteTitleImageFrame.size.height, 
                                       self.view.bounds.size.width, 500);    

    UIView *backgroundPattern = [[UIView alloc] initWithFrame:noteImageFrame];
    backgroundPattern.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Notepaper-iPhone-Line"]];
    [self.scrollView addSubview:backgroundPattern];
    [self.view sendSubviewToBack:backgroundPattern];
    [backgroundPattern release];

    // Add the textView
    CGRect textViewFrame = CGRectMake(noteImageFrame.origin.x+27, 
                                      noteImageFrame.origin.y-3, 
                                      noteImageFrame.size.width-35,
                                      noteImageFrame.size.height);

    RLTextView *textView = [[RLTextView alloc] initWithFrame:textViewFrame];
    self.noteTextView = textView; [textView release];
    self.noteTextView.font = [UIFont fontWithName:@"Cochin" size:21];
    self.noteTextView.backgroundColor = [UIColor clearColor];
    self.noteTextView.delegate = self;
    self.noteTextView.scrollEnabled = NO;
    [self.scrollView addSubview:self.noteTextView];
}

- (void)doneButton:(id)sender
{
    [self.view endEditing:TRUE];
}

// When the keyboard is shown, the UIScrollView's frame shrinks so that it fits in the
// remaining space
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    float kbHideDuration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    self.keyboardHideDuration = kbHideDuration;
    self.keyboardSize = kbSize;
    self.scrollView.frame = CGRectMake(self.view.bounds.origin.x, 
                                       self.view.bounds.origin.y, 
                                       self.view.bounds.size.width, 
                                       self.view.bounds.size.height - kbSize.height);    
}

// When the user presses 'done' the UIScrollView expands to the size of its superview
// again, as the keyboard disappears.
- (void)textViewDidEndEditing:(UITextView *)textView
{
    [UIScrollView animateWithDuration:keyboardHideDuration animations:^{self.scrollView.frame = self.view.bounds;}];
}

// This method needs to get called whenever there is a change of cursor position in the text box
// That means both textViewDidChange: and textViewDidChangeSelection:
- (void)scrollToCursor
{
    // if there is a selection cursor…
    if(noteTextView.selectedRange.location != NSNotFound) {
        NSLog(@"selectedRange: %d %d", noteTextView.selectedRange.location, noteTextView.selectedRange.length);

        // work out how big the text view would be if the text only went up to the cursor
        NSRange range;
        range.location = noteTextView.selectedRange.location;
        range.length = noteTextView.text.length - range.location;
        NSString *string = [noteTextView.text stringByReplacingCharactersInRange:range withString:@""];
        CGSize size = [string sizeWithFont:noteTextView.font constrainedToSize:noteTextView.bounds.size lineBreakMode:UILineBreakModeWordWrap];

        // work out where that position would be relative to the textView's frame
        CGRect viewRect = noteTextView.frame;  
        int scrollHeight = viewRect.origin.y + size.height;
        CGRect finalRect = CGRectMake(1, scrollHeight, 1, 1);

        // scroll to it
        [self.scrollView scrollRectToVisible:finalRect animated:YES];
    }
}

// Whenever the text changes, the textView's size is updated (so it grows as more text
// is added), and it also scrolls to the cursor.
- (void)textViewDidChange:(UITextView *)textView
{
    noteTextView.frame = CGRectMake(noteTextView.frame.origin.x, 
                                    noteTextView.frame.origin.y, 
                                    noteTextView.frame.size.width, 
                                    noteTextView.contentSize.height);
    self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, 
                                             noteTextView.frame.size.height+200);
    [self scrollToCursor];
}

// The textView scrolls to the cursor whenever the user changes the selection point.
- (void)textViewDidChangeSelection:(UITextView *)aTextView 
{
    [self scrollToCursor];
}

// PROBLEM - the textView does not scroll until the user starts typing - just selecting
// it is not enough. 
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [self scrollToCursor];
}
3

3 Answers

5
votes

Cool that you found my post about it, glad it was helpful!

I believe you may not be seeing the bottom line because of this line:

CGRect finalRect = CGRectMake(1, scrollHeight, 1, 1);

You're creating a 1x1 point box. A single line of text might be something like 20 or 30 points tall (depending on font size). So if you're scrolling this point to visible, it may only be showing the very top pixel of the bottom line - making the bottom line effectively invisible! If you make finalRect a little taller so it covers the whole line, it might work better:

CGRect finalRect = CGRectMake(1, scrollHeight, 1, 30);

Also, you may be calling your scrollRectToVisible code multiple times at once, which can cause "judders". In my code, I only run scrollRectToVisible from textViewDidChangeSelection, and resize the UITextView (if needed) in textViewDidChange. UIScrollView (and by inheritance UITableView) has built-in support to scroll the actively selected element to be visible, which in my testing worked well when simply resizing the UITextView while typing (but not when selecting a specific point inside with a touch).

1
votes

There is no easy way to find the screen coordinates for any text or cursor in a UITextView.

What you should do is registering for UIKeyboardWillShowNotification and UIKeyboardWillShowNotification. And in the callbacks you adjust the size or contentInsets of the UIScrollView to adjust for the size of the keyboard.

The size of the keyboard, and even the animation duration is provided in the notifications userInfo, so you can do it in a nice animated fashion.

You find more information and sample code here: http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

1
votes

Not strictly an answer to your question, but here's a different approach to the notes lined background trick: http://www.cocoanetics.com/2010/03/stuff-you-learn-from-reverse-engineering-notes-app/

I've used it and it works well.