0

I have a collection view inside of UIViewController. The view controller also has another UIView (let's call it welcomeView) which is placed above the collection view. When I scroll through the collection view, I would like the welcomeView to scroll with it. I have looked at this answer https://stackoverflow.com/a/43215801/5124961 which pretty much sums up how id like it to look, minus the view sticking to the top. The only problem with that solution is that my collectionView already has a header, so adding the welcomeView as a sublayer to collection view adds it under the already existing header which I dont want.

by just using this snippet of code:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offset = collectionView.contentOffset.y
    if(offset > 0){
        self.welcomeView.frame = CGRect(x: 0, y: -offset, width: self.view.bounds.size.width, height: 100)
    }else{
        self.welcomeView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 100)
    }
}

I get this effect:

enter image description here

I think the frame of the collection view has to change depending on the offset but not too sure on how to achieve this after playing around with it. I have also looked at a few other questions similar to mine, however, these were in objective C which I am not too familiar with. Does anyone have a solution? thank you.

Andrew Harris
  • 396
  • 7
  • 24

1 Answers1

0

If I guess correctly from your capture, your welcome view doesn't overlay the collection view.

Based on this guess, the solution would be:

  1. make the collection view go to the top of your controller's view
  2. your welcome view can overlap your collection view
  3. to avoid that the welcome view overlaps the content of your collection view, modify the contentInset property of your collection view (the contentInset's top should be equal to the welcome view's height).
  4. keep your snippet
  5. the scroll indicator will probably disappear under the welcome view. A simple solution is to have a transparent background to the welcome view. Thanks to the contentInset and the delegate call, you're guaranteed that there's no overlap between the content of the collection view and the welcome view.
Renaud
  • 380
  • 4
  • 13