迅速:滚动collectionView

时间:2018-07-18 08:23:36

标签: ios swift

我有collectionView,并且我想在单击按钮时滚动到下一部分。该怎么做?

func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4  
    }

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }

@IBAction func nextAction(_ sender: Any) {
        //scroll to next
    }

更新

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        cellOffset = 10

        cellWidth = (collectionView.bounds.width / 3)  - (cellOffset * 4)
        cellHeight = (cellWidth / 2 * 3) + (cellWidth / 2 * 0.65)

        return CGSize(width: cellWidth, height: cellHeight)
    }

3 个答案:

答案 0 :(得分:0)

假设您有一个变量,可以跟踪当前滚动的部分。

@IBAction func nextAction(_ sender: Any) {

    let attr = collectionView.layoutAttributesForItem(at: IndexPath.init(row: 0, section: currentSection))
    collectionView.setContentOffset(attr!.frame.origin, animated: true)
    currentSection += 1;
    if currentSection >= maxSectionCount {
        currentSection = maxSectionCount - 1
    }
}

答案 1 :(得分:0)

这可以通过一些简单的步骤完成:

  • 找到当前可见的第一个部分的部分编号
  • 如果节号不是最后一个节,则在其上加1
  • 滚动到具有新版块编号的版块

    let currentlyVisibleSection = collectionView.indexPathsForVisibleItems.map { $0.section }.min()!
    if currentlyVisibleSection < 3 {
        let scrollToSection = currentlyVisibleSection + 1
        collectionView.scrollToItem(at: IndexPath(item: 0, section: scrollToSection), at: .top, animated: true)
    
    }
    

答案 2 :(得分:0)

func goToNextSection() {
    guard let nextIndex = getNextSectionIndex() else {
        return
    }
    goToItemAt(nextIndex)
}

func getNextSectionIndex() -> IndexPath? {
    guard let firstVisibleCell = mycollection.visibleCells.first, // maybe last in your scenario
        let indexOfFirstCell = mycollection.indexPath(for: firstVisibleCell) else {
        return nil
    }
    let nextIndex = IndexPath(item: 0, section: indexOfFirstCell.section + 1)
    let yesIhaveCellsHere = true // you need to check if your DS has 'cells' for this, otherwise it will crash at scroll to item
    guard yesIhaveCellsHere else {
        return nil
    }
    return nextIndex
}

func goToItemAt(_ index: IndexPath) {
    mycollection.scrollToItem(at: index,
                              at: UICollectionViewScrollPosition.left, // adjust for your scenario
                              animated: true)
}