Scrolling UIScrollView to display the lowest of several text fields

I have UIScrollViewone that has several dynamic views inside it, each of which has a text box. When I start typing in one of the fields, I want the scroll to be visible, so that the field is at the top of the screen (visible above the keyboard). It works great; here is the code:

(void)didStartTyping:(id)sender {
    [scrollView setContentOffset:CGPointMake(0, subView.frame.origin.y) animated:YES];
    scrollView.scrollEnabled = NO;
}

(void)didFinishTyping:(id)sender {
    scrollView.scrollEnabled = YES;
}

But whenever scrolling is scanned to the very top, and I start typing in the lowest visible text box, it doesn't scroll far enough (short by about 40 pixels). The mysterious thing is that it works if I scroll only one pixel from the top of the scroll, but when I scroll up, it behaves differently.

+5
1

, , - , scrollview, textViewDidBeginEditing: called. im tableview, scrollview, , . scrollToRowAtIndexPath, scrollRectToVisible

//setup keyboard callbacks
- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:nil];
}

- (void)keyboardWillShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
}

//this is called from your UITextViewDelegate when textViewDidBeginEditing: is called
- (void)updateActiveTextScroll:(UITextView*)textView
{
    activeTextView = textView;
    UIEdgeInsets inset;
    UIInterfaceOrientation orient = [[UIApplication sharedApplication] statusBarOrientation];
    if( UIInterfaceOrientationIsLandscape(orient) )
    {
        inset = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.width, 0.0);
    }
    else
    {
        inset = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.height, 0.0);
    }
    myTableView.contentInset = inset;
    myTableView.scrollIndicatorInsets = inset;

    [myTableView scrollToRowAtIndexPath:activeNSIndexPath
                       atScrollPosition:UITableViewScrollPositionBottom
                               animated:YES];
}

//dont forget to reset when the keyboard goes away
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets inset = UIEdgeInsetsZero;
    myTableView.contentInset = inset;
    myTableView.scrollIndicatorInsets = inset;
}
+2

All Articles