无法在 swift 中一次水平滚动两个集合视图

问题描述 投票:0回答:1

我在滚动视图中有两个集合视图。如果我水平滚动,那么我需要同时滚动两个集合视图

代码: 在下面的代码中,如果我首先滚动 collectionview,然后第一个 collectionview 第一个单元格滚动,然后第二个 collectionview 的单元格滚动。但我需要同时滚动两个 collectionviews

这里

qrCollectionView
adCollectionView
是两个collectionviews

func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.isEqual(qrCollectionView), scrollView.isDragging {
       var offset = adCollectionView.contentOffset
       offset.x = qrCollectionView.contentOffset.x
    adCollectionView.setContentOffset(offset, animated: true)
   } else if scrollView.isEqual(adCollectionView), scrollView.isDragging {
       var offset = qrCollectionView.contentOffset
       offset.x = adCollectionView.contentOffset.x
       qrCollectionView.setContentOffset(offset, animated: true)
   }
}

需要这样:如果我使用两个按钮那么它的工作完美..当我手动滚动而不是按钮点击时我需要这样,怎么样?请指导我

@IBAction func leftButton(_ sender: UIButton) {

if currentItem != 0, currentItem != nil {

    currentItem! -= 1
    let indexPath = IndexPath(item: currentItem!, section: 0)
    qrCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    adCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)

} else {
    print("No item to go to previous left")
}
}

@IBAction func rightButton(_ sender: UIButton) {

guard let totalItems = ticketListtData?.result?.tickets?.count else { return }
if currentItem! < totalItems - 1 {
    currentItem! += 1
    let indexPath = IndexPath(item: currentItem!, section: 0)
    qrCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    adCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)

} else {
    print("No item to go to next right")
}
}
swift uicollectionview uiscrollview
1个回答
0
投票

假设您的两个集合视图具有相同的 contentOffset。

func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == qrCollectionView {
            adCollectionView.contentOffset.x = scrollView.contentOffset.x
        }else {
            qrCollectionView.contentOffset.x = scrollView.contentOffset.x
        }
    }

对我来说它工作正常。确保每次滚动时 scrollViewDidScroll 都在调用。

© www.soinside.com 2019 - 2024. All rights reserved.