Setting Contentoffset Programmatically Triggers Scrollviewdidscroll

Setting contentOffset programmatically triggers scrollViewDidScroll

It is possible to change the content offset of a UIScrollView without triggering the delegate callback scrollViewDidScroll:, by setting the bounds of the UIScrollView with the origin set to the desired content offset.

CGRect scrollBounds = scrollView.bounds;
scrollBounds.origin = desiredContentOffset;
scrollView.bounds = scrollBounds;

scrollViewDidScroll: when scroll programmatically?

There might be a better solution but this should work :

Declare a boolean in your .h

@property(nonatomic,assign) BOOL scrollingProgrammatically;

And in your .m :

self.scrollingProgrammatically = YES;
[scroller scrollRectToVisible:CGRectMake(0, 0,scroller.frame.size.width,scroller.frame.size.height) animated:YES];

...

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
if(!self.scrollingProgrammatically){
...
}
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
self.scrollingProgrammatically = NO;
}

Where / when set contentOffset?

try to use it in viewDidLayoutSubviews

How to tell if the user dragged the scroll view vs. me setting the content offset

Use scrollViewWillBeginDragging. This method does not get called when programmatically setting the offset.

UITableView: scrollViewDidScroll executes and contentOffset jumps when gestureRecognizers active

I found that disabling the option Adjust Scroll View Insets (in IB or in Code), even though marked as the right answer on some similar posts, is only part of the equation.

Some constraints were not set properly on the UITableView and that caused the bug.
Getting all the constraints right (or deleting them completely) and disabling the aforementioned option fixed it for me.



Related Topics



Leave a reply



Submit