Parallax UIScrollView – handling two views in one

2019-09-02 18:28发布

问题:

I’m creating a basic parallax effect much like the iOS7 app switcher, using two UIScrollView instances (cardScrollView and tileScrollView). I scroll one alongside the other, at a different rate, like so:

if ([scrollView isEqual:self.tileScrollView]) {
    [self.cardScrollView setContentOffset:CGPointMake((self.tileScrollView.contentOffset.x + 110) * TILE_CARD_DELTA,
                                                      self.cardScrollView.contentOffset.y)];
}

This works fine when scrolling tileScrollView. However, I’d like the same to work in reverse, meaning I can scroll cardScrollView and have tileScrollView move accordingly. The issue I’m having is that calling setContentOffset actually causes cardScrollView to call scrollViewDidScroll itself, meaning they’re continually trying to set each other at the same time, and all kinds of hell break loose.

Basically, the issue here is that both scrollView instances are relying on the same scrollViewDidScroll, and so I can’t differentiate between the two of them in there.

How can I get around this one?

回答1:

You are getting reference of both in this method and work as per requirement :

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

 {
   if (scrollView == self.tileScrollView) {
      // do something
   }
   else {
      // do something
   }
  }