Search code examples
iosparallaxhorizontal-scrolling

Horizontal scrolling with parallax background for ios


I'm facing a challenge of creating an introduction view, something like the "Cleanio" app (https://itunes.apple.com/fr/app/cleanio-pressing-la-demande/id885856031?mt=8).
Here is how it looks like:
enter image description here enter image description here enter image description here


So, the background and the overlay are moving independently and not in the same speed.
Does anyone have a start point how to realize that?


Solution

  • Yep.

    What you need is two UIScrollViews. These should both be subviews of the main view (not contained in each other.

    The bottom one has your image in it and the top one has the content.

    Call them imageScrollView and contentScrollView.

    Become the delegate of contentScrollView.

    The contents will look something like this...

    contents:    [---page 1---][---page 2---][---page 3---][---page 4---]
    image:       [------------the image------------]
    screen:      [---screen---]
    

    Key is that image is smaller than all the pages and bigger than the screen.

    The frames of the scrollviews are the same width as the screen. This diagram is just to show the content widths not the frame widths.

    So, the screen stays where it is and the two scroll views move over it.

    Now the parallax part...

    - (CGFloat)maxOffsetForScrollView:(UIScrollView *)scrollView
    {
        CGFloat contentWidth = scrollView.contentSize.width;
        CGFloat frameWidth = CGRectGetWidth(scrollView.frame);
    
        return contentWidth - frameWidth;
    }
    
    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        // this is the delegate method for the content scroll view.
        // I'm only doing horizontal stuff here, you can do vertical too if you want
    
        CGFloat maximumContentOffset = [self maximumOffsetForScrollView:self.contentScrollView];
        CGFloat currentOffset = self.contentScrollView.contentOffset.x;
    
        CGFloat percentageOffset = currentOffset/maximumContentOffset;
    
        CGFloat maximumImageOffset = [self maximumContentOffsetForScrollView:self.imageScrollView];
        CGFloat actualImageOffset = maximumImageOffset * percentageOffset;
    
        [self.imageScrollView setContentOffset:CGPointMake(actualImageOffset, 0)];
    }
    

    This takes the percentage offset from the content view and offsets the image view by the same percentage offset.

    The result is a parallax effect. You can make it faster or slower by changing the relative sizes of the image and the content. More pages (or smaller image) = slower parallax.