I struggled with a problem with UIScrollView for a long time.
I have a UIScrollVIew that contains a UITextView as a subview. When I select a text view, a keyboard appears. I want to resize the text view so that it exactly matches the available space, and also scroll to scroll so that the text view is located exactly in the visible space (not hidden by the keyboard).
When the keyboard appears, I call a method that calculates the appropriate size for the text view, and then executes the following code:
[UIView animateWithDuration:0.3 animations:^ { self.textView.frame = frame; } ]; [self.scrollView setContentOffset:CGPointMake(0,frame.origin.y) animated:YES];
(here the frame is the corresponding frame for the text view).
Unfortunately, the scroll view will not always move to the desired position, especially when it is already in a non-zero vertical offset of the content when I select the text view. I know that the content offset that I set is correct.
After much testing, I finally realized that what happened was that after the animation ended, the scroll automatically scrolled.
This code works:
UIView animateWithDuration:0.3 animations:^ { self.textView.frame = frame; } completion:^(BOOL finished) { [self.scrollView setContentOffset:CGPointMake(0, frame.origin.y) animated:YES]; } ];
but it looks weird because the scroll scrolls to the wrong position and then to the right.
Does anyone know how I can prevent a scroll view from changing its content offset when the frame of a text view completes its animation?
I am testing using iOS 5.0.
Here is the solution I found that works. I still do not quite understand what is happening, perhaps this has something to do with how my springs and struts are installed. I basically reduce the size of the contents of the scroll view by the same amount as the text view.
- (void)keyboardDidShow:(NSNotification*)aNotification { NSDictionary* info = [aNotification userInfo];
( [self updateViewLayout] is a method that returns the text view to the correct height and resets the size of the scroll content, and also ensures that all other subviews are correctly positioned).