Synchronize scrolling with two collection views in Swift?

自闭症网瘾萝莉.ら 提交于 2021-02-07 10:54:32

问题


Is there a practice to scroll a collection view with cells, and, depending on its content offset, scroll the other collection view?

I have a main collection view that has two cells and scrolls horizontally. Then I have a second collection view with cells that scrolls vertically. What happens is when I scroll up, then scroll horizontally to the second vertical cv, it's not synced with relation to the first.

I overrode the scrollViewDidScroll inside the vertically scrolling collection view (not the main one, because it scrolls horizontally), to no avail (** means the parts that don't work to achieve my effect).

var didScrollPastProfileView: Bool = false

func scrollViewDidScroll(scrollView: UIScrollView) {
    let collectionViewDictionary = ["scrollView": self.collectionView]
    NSNotificationCenter.defaultCenter().postNotificationName("cvDidScroll", object: nil, userInfo: collectionViewDictionary)

if scrollView.contentOffset.y > 250 {

    **self.didScrollPastProfileView = true
    if self.didScrollPastProfileView {
       let previousContentOffset = scrollView.contentOffset.y
       scrollView.contentOffset.y = previousContentOffset
    }**

    } else if scrollView.contentOffset.y < 250 {

        **let previousContentOffset = scrollView.contentOffset.y
        scrollView.contentOffset.y = previousContentOffset
        self.didScrollPastProfileView = false**
    }

}

Here's a visual:

Notice how there's space above when I scroll to the second cell? I want that vertical scroll view to follow the first. Any suggestions?

EDIT: I tried to access the second cell of the horizontal collection view while I was scrolling in the first cell, and I tried to change contentOffSet.y when I scrolled down in the first one, but I got an EXC_BAD_ACCESS error.

if scrollView.contentOffset.y <= 250.0 {
        let groupsPosts = childViewControllerForPosts.collectionView(childViewControllerForPosts.collectionView!, cellForItemAtIndexPath: NSIndexPath(forItem: 1, inSection: 0)) as! FeedCell
        groupsPosts.collectionView.contentOffset.y =  -scrollView.contentOffset.y

        self.topVerticalConstraint?.constant = -scrollView.contentOffset.y

回答1:


You can do something like this when scrolled to the collectionViewB with animated to false so it look like it is synchronised.

let indexPath = collectionViewA.indexPathsForVisibleItems().first
self.collectionViewB.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Top, animated: false) 

Not exactly sure how you set up this two collection. If you do not have access to collectionViewA then you might have to save the current indexPath to a variable and pass it over.



来源:https://stackoverflow.com/questions/39008620/synchronize-scrolling-with-two-collection-views-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!