简体   繁体   中英

Swift - Scroll in Horizontal CollectionView stopped working inside a UIScrollView

Here's a tricky one...

I have a ScrollView inside of a View Controller with multiple CollectionViews inside. The CollectionViews are setup for profile photos for horizontal scrolling.

I want the ScrollView to scroll Vertical, but not Horizontal. I used the following code to do this with the ScrollView:

    func scrollViewDidScroll(scrollView: UIScrollView) {
    if scrollView.contentOffset.x>0 {
        scrollView.contentOffset.x = 0
    }

    if scrollView.contentOffset.x < 0 {
        scrollView.contentOffset.x = 0
    }
}

This works as expected, and I used UIScrollViewDelegate and set the ScrollView as:

self.scrollView.delegate = self

Now the tricky part... the CollectionViews no longer scroll horizontally. I'm assuming that is because the parent ScrollView is taking over the view, and/or the code above is also preventing the horizontal scroll in the CollectionViews.

Anyone have some ideas on how I an achieve what I am looking to?

Cheers, Aaron

Try something like this in your scrollViewDidScroll method

func scrollViewDidScroll(scrollView: UIScrollView) {
    if (scrollView == self.scrollView) {
        if scrollView.contentOffset.x>0 {
            scrollView.contentOffset.x = 0
        }

        if scrollView.contentOffset.x < 0 {
            scrollView.contentOffset.x = 0
        }
    }
}

Because collectionView also have delegate of scrollView.
Hope this will help you.

I would suggest using the UICollectionView instead of UIScrollView in your case. Seems like your horizontally scrolling collections of images are pretty similar, thus it would be more logically to represent each as a prototype cell of the high-level parent UICollectionView . This will also fix your scrolling issues in a natural way =)

More precisely, you will have a parent UICollectionView with the Scroll direction set to Vertical, owning a UICollectionViewCell with the inner child UICollectionView having the Scroll direction set to Horizontal.

Here is the example how you can do this using the storyboard (look at the second prototype cell):

在此处输入图片说明

In your case, you will just need to fill the child UICollectionView with the images instead of the labels, which were used in my example.

Hope, this will help you. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM