Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't fully understand scrollRectToVisible when I'm using contentInset

I added very big text to UItextView. My initial offset is -55. Then I scrolled to the bottom of UITextView. My offset is 406.

Then I called scrollToZero. My offset is -55. I called scrollToZero again and my offset is 0. Why is scrollToZero so unpredictable? I don't undestand why offset changed when I clicked again.

-(void) viewDidLoad
{
 [super viewDidLoad];
 textView.text = @"Very big text";
 textView.contentInset = UIEdgeInsetsMake(55.0, 0, 0, 0);
 [textView scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO];
}

-(IBAction) scrollToZero:(id)sender
{
 [textView scrollRectToVisible:CGRectMake(0, 0, textView.frame.size.width, textView.frame.size.height) animated:NO];
}
-(IBAction) onLog:(id)sender
{
 NSLog(@"___content offset %f", textView.contentOffset.y);
}
like image 860
Voloda2 Avatar asked Mar 22 '12 10:03

Voloda2


1 Answers

I have been battling this very problem. I am convinced that this is a bug in the UIScrollView class, I can see no other explanation.

First set your insets to zero, call scrollRectToVisible:animated:, and then restore your insets. It only matters if the scroll-to rect is 'left of' the current rect. 'right of' works as expected.

CGRect rect = self.scrollView.bounds;
CGRect scrollToRect = CGRectOffset(rect, scrollDelta, 0);

if (CGRectIsLeftOfRect(scrollToRect, rect)) {
    UIEdgeInsets insets = self.carouselView.contentInset;
    self.scrollView.contentInset = UIEdgeInsetsZero;
    [self.scrollView scrollRectToVisible:scrollToRect animated:animated];
    self.scrollView.contentInset = insets;
} else {
    [self.scrollView scrollRectToVisible:scrollToRect animated:animated];
}
like image 165
emp Avatar answered Oct 17 '22 02:10

emp